Calling C functions at runtime with Inline Assembly

Programming, for all ages and all languages.
Post Reply
babi2ki
Posts: 1
Joined: Tue Aug 03, 2010 1:34 am

Calling C functions at runtime with Inline Assembly

Post 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
gerryg400
Member
Member
Posts: 1801
Joined: Thu Mar 25, 2010 11:26 pm
Location: Melbourne, Australia

Re: Calling C functions at runtime with Inline Assembly

Post by gerryg400 »

Isn't this a job for stdarg ?
If a trainstation is where trains stop, what is a workstation ?
User avatar
Owen
Member
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

Post 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
gerryg400
Member
Member
Posts: 1801
Joined: Thu Mar 25, 2010 11:26 pm
Location: Melbourne, Australia

Re: Calling C functions at runtime with Inline Assembly

Post 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 ?
If a trainstation is where trains stop, what is a workstation ?
Post Reply