views:

304

answers:

6

I remember seeing a way to use extended gcc inline assembly to read a register value and store it into a C variable. I cannot though for the life of me remember how to form the asm statement. Any help is much appreciated.

+1  A: 

Isn't this what you are looking for?

Syntax:

 asm ("fsinx %1,%0" : "=f" (result) : "f" (angle));
Kornel Kisielewicz
You do realize that's going to read one variable, compute the sine and then store the result in a second variable.
R Samuel Klatchko
@Samuel: That was an example of the syntax only.
Kornel Kisielewicz
+1  A: 

I don't know about gcc, but in VS this is how:

int data = 0;   
__asm
{
    mov ebx, 30
    mov data, ebx
}
cout<<data;

Essentially, I moved the data in ebx to your variable data.

Jacob
x86-only, of course. Microsoft's compilers for x64 and Itanium do not support inline assembly.
ephemient
+5  A: 

Here is a way to get ebx:

int main()
{
    int i;
    asm("\t movl %%ebx,%0" : "=r"(i));
    return i + 1;
}

The result:

main:
    subl    $4, %esp
    #APP
             movl %ebx,%eax
    #NO_APP
    incl    %eax
    addl    $4, %esp
    ret


Edit:

The "=r"(i) is an output constraint, telling the compiler that the first output (%0) is a register that should be placed in the variable "i". At this optimization level (-O5) the variable i never gets stored to memory, but is held in the eax register, which also happens to be the return value register.

Richard Pennington
A: 

This will move the stack pointer register into the sp variable.

intptr_t sp;
asm ("movl %%esp, %0" : "=r" (sp) );

Just replace 'esp' with the actual register you are interested in (but make sure not to lose the %%) and 'sp' with your variable.

R Samuel Klatchko
+1  A: 
ephemient
A: 

From the GCC docs itself: http://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html