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
Calling C functions at runtime with Inline Assembly
Re: Calling C functions at runtime with Inline Assembly
Isn't this a job for stdarg ?
If a trainstation is where trains stop, what is a workstation ?
- Owen
- Member
- Posts: 1700
- Joined: Fri Jun 13, 2008 3:21 pm
- Location: Cambridge, United Kingdom
- Contact:
Re: Calling C functions at runtime with Inline Assembly
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
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
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 ?
If a trainstation is where trains stop, what is a workstation ?