2016-05-15 54 views
0

我创建了一个具有结构的数组,我需要使用索引和指向数组的指针从数组中获取结构。x86程序集 - 从具有结构的数组中获取结构

struct T{ 
    char a, b, c, d, e, f, g; 
}; 

T CtiPrvekPole1(T *pole, int index){ 
    T result; 
    _asm{ 
     mov eax, pole; 
     mov ebx, index; 
     mov eax, [eax + ebx * 8]; 
     mov result, eax; 
    } 
    return result; 
} 

int _tmain(int argc, _TCHAR* argv[]) 
{ 

    T struct1, struct2, struct3, struct4; 

    struct1.a = 1; 
    struct1.b = 2; 
    struct1.c = 3; 
    struct1.d = 4; 
    struct1.e = 5; 
    struct1.f = 6; 
    struct1.g = 7; 

    struct2.a = 8; 
    struct2.b = 9; 
    struct2.c = 10; 
    struct2.d = 11; 
    struct2.e = 12; 
    struct2.f = 13; 
    struct2.g = 14; 

    struct3.a = 15; 
    struct3.b = 16; 
    struct3.c = 17; 
    struct3.d = 18; 
    struct3.e = 19; 
    struct3.f = 20; 
    struct3.g = 21; 

    struct4.a = 22; 
    struct4.b = 23; 
    struct4.c = 24; 
    struct4.d = 25; 
    struct4.e = 26; 
    struct4.f = 27; 
    struct4.g = 28; 

    T pole1[] = { struct1, struct2, struct3, struct4 }; 

    T result = CtiPrvekPole1(pole1, 2); 
    printf("Cti prvek pole1 : %c\n", result.b); 

} 

我应该如何获得该结构?我使用了8个字节,因为一个结构有7个字节,所以它应该有8个字节的对齐。我对吗?

谢谢。

回答

0

你的想法是正确的,但你的代码是不正确的。您有:

T CtiPrvekPole1(T *pole, int index){ 
    T result; 
    _asm{ 
     mov eax, pole; 
     mov ebx, index; 
     mov eax, [eax + ebx * 8]; 
     mov result, eax; 
    } 
    return result; 
} 

所以你移动一个地址(指针)必须清楚交代通过result占据了前四个字节的内存。你需要移动数据。

C代码这样做将是:

T result; 
result = pole[index]; 
return result; 

即拷贝从pole[index]阵列8个字节成result,然后返回结果。

实际上,您甚至不需要CtiPrvekPole1方法。你可以写:

T pole1[] = { struct1, struct2, struct3, struct4 }; 
T result = pole1[2]; 

如果你真的想用汇编语言来做,那么你必须得到源地址和目标地址并复制。以下是一种方法:

T CtiPrvekPole1(T *pole, int index){ 
    T result; 
    _asm{ 
     mov eax, pole; 
     mov ebx, index; 
     mov ecx, [eax + ebx * 8]; // ecx = source address 
     lea edx, result   // edx = destination address 
     // copy first four bytes 
     mov eax, [ecx] 
     mov [edx], eax 
     // copy next four bytes 
     mov eax, [ecx+4] 
     mov [edx+4], eax 
    } 
    return result; 
}