passing arguments between c and inline assembly

爷,独闯天下 提交于 2019-12-11 12:19:45

问题


I have a question about passing arguments between c and inline assembly

I'm having trouble passing an array into my inline assembly. I keep getting the error 'error: memory input 1 is not directly addressable'

Here is an example of my code:

void main()
{
    char name[] = "thisisatest";
        __asm__ ("\
        .intel_syntax noprefix     \n\
        mov eax, %[name]           \n\
        inc (eax)                  \n\
       "
    :/*no output*/
    :[name]"m"(name)
    );
}

This should increment the first letter of my string (making it 'u'), but it doesn't build.

Ideas?


回答1:


Incase anyone else comes across this I got it working.

void main()
{
    char name[] = "thisisatest";
        __asm__ ("\
        .intel_syntax noprefix     \n\
        lea, eax, %[name]          \n\
        inc BYTE PTR [eax]          \n\
       "
    :/*no output*/
    :[name]"m"(name[0])
    );
}

The key was passing in the first element of the array as a memory parameter, then asking for the effective address. I then had a pointer to my string. Hope this helps others




回答2:


You can't pass arrays into inline assembly (except contained in structs) as they convert to pointers, and you can't apply a memory constraint to that pointer as it isn't an lvalue.

You can pass an element of an array in:

asm ("incb %0" : "+g" name[0] : : ); // AT&T syntax

Or it address:

asm volatile ("incb (%0)" : : "r" name : "memory"); // AT&T syntax

Also if you switch assembler syntax in inline assembler you must restore it afterwards and not use memory asm operands as these will be in the wrong syntax.

Edit: omitted the variable name in the second code fragment, and added a bracket in the first.




回答3:


Don't do &name try just name, an array always points to the space in memory where it is located. Right now what you're trying to do is putting the array 'thisisatest' into a register (eax) that can't hold so much data.

The register can either hold a few chars (depending on register size) or the address of where the array is located



来源:https://stackoverflow.com/questions/19455923/passing-arguments-between-c-and-inline-assembly

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