Page 1 of 1

Calling C functions at runtime with Inline Assembly

Posted: Tue Aug 03, 2010 1:40 am
by babi2ki
Hi,
Am working on a project where I have to invoke c functions at runtime, without knowing type of arguments it takes. So I have function pointer and variable size list of arguments. The only way that I could think of to do this with using inline assembly.

Using assembly, I was able to push the arguments onto the stack and then invoke this function.

Here is the sample code, for linux x86.
---------------------------------------------------------------------------------------------------------------------------

void* dlib;
int count = 4;
float v[]={2.34, 3.45, 4.56, 5.67};

dlib = dlopen ("Lib path", RTLD_NOW);
void *function;

function = dlsym(dlib, "fun");

for (int i = count - 1; i >= 0; i-- )
{
asm ("pushl %0": : "g" (v) );
}

asm( "call %0": : "g" (function));
------------------------------------------------------------------------------------------------------------------------------------

This is working fine for all the data types except for double.

So here my question is, does anyone know how to invoke function with double data type arguments? Do I need to use a different instruction other than pushl, I used to push other data types on to the stack.

Regards,
Javahar

Re: Calling C functions at runtime with Inline Assembly

Posted: Tue Aug 03, 2010 2:07 am
by gerryg400
Isn't this a job for stdarg ?

Re: Calling C functions at runtime with Inline Assembly

Posted: Tue Aug 03, 2010 6:12 am
by Owen
Aaah! Aaah!AAAAAAAH!

Give it a short while and your code will break. Specifically, you're pushing stuff onto the stack and continuing to execute C code while you have the stack modified - without notifying the compiler.

Secondly, you're not removing the parameters from the stack afterwards. Thirdly, if you port to another architecture you'll need a complete rewrite.

My suggestion? Use libFFI. It does exactly what you want (and more!), is very well ported, and already exists

Re: Calling C functions at runtime with Inline Assembly

Posted: Tue Aug 03, 2010 6:19 am
by gerryg400
Aren't we simply trying to pass an array to a function ? What about just passing the int count, the pointer v and a flag saying the type of the elements of v ?