Invoking native code with hand-written assembly

旧巷老猫 提交于 2019-12-06 00:29:13

You assembly was flawed. There is a difference between

void DoSomething(int *x)
{
    __asm
    {
        mov x[0], 10   // wrong
            mov [x], 10    // also wrong
        mov esi,x      // first get address
        mov [esi],500  // then assign - correct
    }
}

The first two examples did not write to the memory location pointed to the pointer but to the storage location of the pointer itself. Since the parameter comes from the stack you did overwrite with the movups instruction your stack. You can see this in the debugger window when you call e.g.

int x=0;
DoSomething(&x);

With mov [x],10 you do not set x to 10 but you write into your stack.

The alignment correction is wrong. You need to add alignment-misalignment to correct the alignment. So the code should read:

mAlignedBuffer = 
    new IntPtr(mUnmanagedBuffer.ToInt64() + alignment - misalignment);

However, I would recommend that you test the function in a native setting first. Once you know it works there you can move to the managed setting and know that any problems are due to the managed code.

I find out a solution. Loading pointer value on CPU register, and using the register for redirect to memory:

mov esi, result;
movups [esi][ 0], xmm0;

Using those instructions makes the code working as expected.


But the question remain unsolved completely, since the movups instruction can take as first argument a memory address; so if someone knows what's going on, I'm pleased to check the best answer.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!