passing values from Assembly to C

I want to simply pass a variable from assembly over to C and C over to assembly.

The problem is i don't want to use fixed memory addressing (IE. putting the value in a specific location and then using a pointer to access that specific location).

I was initially thinking that i could use registers, but there are only 16 in total! I may have more than 16 values which i want to pass over.

So the next thing i can think of is pushing the values onto the stack. But does this mean i have to use inline assembly to access it in C? something like this:

   asm ( assembler template 
       : output operands                  /* optional */
       : input operands                   /* optional */
       : list of clobbered registers      /* optional */
       );

Is there any other way to go about this? Can anyone give me a REALLY simple example of putting something on the stack, and then accessing it in C code?

Assembly Noob!

Answers


Can you declare a regular C function, call it from C, and allow the compiler to handle the arguments automatically (according to whatever your local convention is)?

If so, you just implement that function using asm, and refer to the named C argument list variables directly.

Eg, using the 68881's fsinx instruction:

float my_fsinx(float angle)
{
    float result;
    asm ("fsinx %1,%0" : "=f" (result) : "f" (angle));
    return result;
}

This example is based on the GCC Extended Asm docs, where you should be able to find some more examples.


Now extended, as per the comment, to handle variable numbers of arguments via a simple pointer & count ...

float my_fsinx_sum(float *angles, int num_angles)
{
    float result, sum;
    int i;
    for (i=0, sum=0; i < num_angles; ++i)
    {
        asm ("fsinx %1,%0" : "=f" (result) : "f" (angles[i]));
        sum += result;
    }
    return sum;
}

No, I'm not sure why you'd want to sum the sines of a bunch of angles either, but hopefully you get the idea. I haven't tried this, so it's possible the angles[i] value needs to be copied out into a local float variable before the asm - try it and see.


You could also use a variable argument-list function, but that's a little more complicated. Without more detail on what you're trying to accomplish and what you've already tried, I can't guess which is better.

Edit -- OK, now I've seen your comment above, you definitely don't want a variable argument-list function: those still have a number of arguments hardcoded at the call site.


Need Your Help

Xcode 7 warning loadNibNamed:owner is deprecated: first deprecated in OS X 10.8

objective-c xcode macos nib

Firstly this issue is for Xcode project written in Objective-C for Mac OSX Application.