【问题标题】:x86 assembly - get structure from an array with structuresx86 程序集 - 从具有结构的数组中获取结构
【发布时间】:2016-09-11 15:39:45
【问题描述】:

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

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 个字节的对齐。我说的对吗?

谢谢。

【问题讨论】:

    标签: arrays data-structures inline-assembly


    【解决方案1】:

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

    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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-07
      • 1970-01-01
      相关资源
      最近更新 更多