Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GCC inline assembly error: Cannot take the address of 'this', which is an rvalue expression

I'm still fighting with GCC - compiling the following inline assembly code (with -fasm-blocks, which enables Intel style assembly syntax) nets me a strange error Cannot take the address of 'this', which is an rvalue expression...

MyClass::MyFunction()
{
    _asm
    {
        //...
        mov ebx, this // error: Cannot take the address of 'this', which is an rvalue expression
        //...
        mov eax, this // error: Cannot take the address of 'this', which is an rvalue expression
        //...
    };
}


Why can I store pointers to different objects in registers, but can't use pointer to MyClass instance?

like image 756
Ryan Avatar asked Jun 03 '11 06:06

Ryan


2 Answers

That's because the compiler might decide on its own to store this in a register (generally ECX) instead of a memory cell, for optimization purposes, or because the calling convention explicitly specifies it should do that.

In that case, you cannot take its address, because registers are not addressable memory.

like image 175
Frédéric Hamidi Avatar answered Oct 12 '22 02:10

Frédéric Hamidi


You can use something like this:

#include <stdio.h>

class A{
public:
    void* work(){
        void* result;
        asm( "mov %%eax, %%eax"
            : "=a" (result) /* put contents of EAX to result*/
            : "a"(this)     /* put this to EAX */
            );
        return result;
    }
};


int main(){
    A a;
    printf("%x - %x\n", &a, a.work());
}

See more details on operands passing to inline asm here

like image 31
elder_george Avatar answered Oct 12 '22 01:10

elder_george