C function call dynamically

Hi.

I need help with a C/C++ question and i hope someone can help me or give me some ideas.

Is possible to build a function C/C++ call dynamically? I.e, i have an array with pointer functions and these functions can have different number of parameters and types. These parameters and their types are stored in a database that i'll get depending on the function name that i want to execute with a function pointer.

More or less i want to build a function thrower with any parameter.

Can i build the function call dynamically?

Any idea?

If you mean something like printf(), you can build something similar with variable arguments using stdarg.h

Thanks Pludi, but, yes, i know that library, but, what i need is something more complex because i have to build the function call without know the parameter number in programming time. I have a number and a list of parameters (void*).

For example, if i get 2 as parameter number, my function call will be:

       execute (param[0], param[1]);

and if it is 5:

    
     execute (param[0], param[1], param[2], param[3], param[4]);

Then, or i have a switch with all the posiblities or i don�t know to do.

To the best of my knowledge, you always have to tell C functions something about their parameters. Taking your example: the function execute should take an arbitrary number of arguments of unknown type, right? So lets say you pass along

  • an int*: is it a pointer to an integer, or just the start of an integer array? If it's the later, how should it know how far to count?
  • an int: is it a number, an address, or the starting address of an array? If it's an address, what's there? A char/long/double?

As you've said, you've got a number and a list of parameters. Is the number the number of parameters in the list? If so, just use the va_* macros for a function:

void execute (int numParam, ...);

or even better

void execute (int numParam, type* params);

If that doesn't suit you, could you give an better example of what you need?

hello
you can use function pointers and call functions dynamically. and use case statements to call the function dynamically
like int (*func1)(arg1,arg2....); //function pointers.

I think the short answer is no. As far as I know, there is no way in C to dynamically control the call stack. You may need to build your own argument list into a structure that can be dynamically composed by the caller and decomposed by the callee. Then, to all your "dynamic" functions, you pass the structure as a single argument.

The only way to use var-args, IMO, would be to know ahead of time the set of argument lists that you can support. You would have to limit the number of items in the set to something manageable by a switch statement. So, for example, if you have 40 procedures and the unique set of argument lists is [ (string), (string, int), (int, int), (string, string, string) ] then you have four different argument lists in the set and you can use a single four item switch statement to make the call after selecting the right function pointer.

However, if you can't limit the number of different argument lists, and you need a generic caller, then things get hairy quickly. No matter what, you have to at least limit the number of types and argument counts you can support. But, the combinations of types and counts quickly increases the number of items in the set that must be supported by the switch statement.

In fact, in the case where you allow (string, int, long) in either 1, 2, or 3 arguments you can have 3+9+27 = 39 different possible argument lists in the set. Make it 1, 2, 3, or 4 arguments it goes up to 120. Make it four different types and four lengths and you will have such a large set you won't want to write the switch statement to manage it; it'll have 4+16+64+256 = 340 switch cases.

As you can see, to make a generic caller in the above cases would get cumbersome.

Quickly, back to the "generic thrower" comment. You must realize that when a function is compiled (in this case your generic thrower function) the compiler configures a stack frame that is large enough to store arguments for the functions called by the "generic thrower". While you could manipulate that stack frame (in an architecture specific way) during runtime to call a function with any arguments you want, the compiler is still in control of the size of the stack frame. Too many, or too large, arguments and you'll overrun the frame and corrupt memory. If you could force the compiler to create a larger than normal stack frame so you'll "never" overrun it then you may be able to read up on how your architecture composes its stack frames to place the arguments into the frame and make a call (with no arguments) to the function and hope what you tweaked into the stack frame sticks around for the function to pick up. But, this won't be pretty code, and it won't be guaranteed to be compatible across different systems.

On more note, I'm not sure all architectures store the arguments for the called function in the frame of the caller. However, I know AIX does. If yours does not, then you're in even bigger trouble because then you need to figure out how to allocate a stack frame yourself, put all the arguments in it, and fire off the call. All of this is, also, architecture specific. And to code it, you're probably looking at dipping into ASM.

Ohhhhhh, thank you very much. You have really understood my problem. I didn�t know if i had explained very well. My english isn�t very good.
Anyway, i am studying a C++ Reflection Library (XCppRefl - C++ Reflection Library), maybe it could serve me.

Sincerely, thank you very much.

I've seen it done, like you say, in inline ASM. Very hairy ASM that's specific to carefully controlled circumstances under one configuration of one compiler of one version of one architecture. I tried building one myself, and quickly gave up when I spotted the optimizer stuffing arguments into registers instead of stack whenever it felt like it.

It should really be up to the one thing that really knows how function calls work at all times -- the compiler, plus macros in stdargs. It's one of the few severely un-orthogonal things left in C but there's obscure reasons this isn't possible on a few strange architectures, ergo it's not going to happen.

Just as a note, I did some quick tinkering and it appears the stack frame for Linux (probably ia32 in general) stores the parameters in the stack frame of the callee. So, in contrast to AIX, coding your generic thrower in Linux will require you to allocate a brand new stack frame, put all the arguments in it, configure it correctly to call the procedure, and fire it off. Non-trivial at best.

Having no experience with the reflection library, I don't know if it can be used to build dynamic calls. If so, great.... But, I have my doubts.

pogdorica - You want an array of function pointers.

/* function pointers - std C allows ([blank])== any number/datatypes of parms  */
#include <stdlib.h>
#include <stdio.h>
void foo1(int p)
{
   printf("function foo1:%d\n", p);
}

void foo2(char *src, const int p)
{
   sprintf(src, "function foo2: %d", p);
   printf("%s\n", src);
}

void foo3(const int a, const int b, const int c)
{
	  int total=a + b + c;
	  printf("function: foo3(): %d + %d + %d = %d\n", a, b, c,  total);
}

typedef void (*ptr2Func)();

int main(int argc, char **argv)
{
   ptr2Func  fx[3]={foo1, foo2, foo3};
   char string[32]={0x0};
   fx[0](9);
   fx[1](string, 4);
   fx[2](1,2,3);
   return 0;
}
# compile with zero errors & warnings
> gcc -Wall -pedantic fptr.c    

>

run it:

> ./a.out                 
function foo1:9            
function foo2: 4               
function: foo3(): 1 + 2 + 3 = 6

Only unoptimized. Optimization can cause unpredictable things -- I've seen gcc do weird things like stuff floating-point doubles into SSE registers when calling fprintf.

Dream Warrior - consider trampolines or indirect function calls found most often in callbacks. I think python uses trampolines to support coroutines. ghostdog would know for sure.

Linux trampoline code is described in great detail in: 'Understanding the Linux Kernel' by Daniel P. Bovet and Marco Cesati.

gcc documentation:
Trampolines - GNU Compiler Collection (GCC) Internals

The lazy man's version -
A trampoline is small code segment, usually a vector, created at run time. It normally lives on the stack, in the stack frame of the 'holding' function.

For mixing pieces of code with incompatible calling conventions, trampolines can convert the caller's convention to the callee's convention. For example, C code that needs to call C++ objects can have a trampoline to change calling conventions.

gcc implements trampolines as nested functions.

Odd...how would fprintf know where to pick them up if not from the stack....?

---------- Post updated at 03:57 PM ---------- Previous update was at 03:52 PM ----------

I'm unsure how this could be used to dynamically figure out the arguments of another function and populate the call stack and call it.... And the man page you posted is above my head :o.

Thank you very much for your suggestions. As i suspected that task is so complicated really.
I 'll try to use an array of function pointers with an only parameter with generic type that it is a list with the type and value of each parameter to the function.
Something such as:

// Struct with parameter info
typedef struct {
        char nombreParametro[30];
        void *valor;
} s_parametro;
typedef ListaParametros List<s_parametro>;

// Struct with function info
typedef struct {
        char nombreFuncion[30];
        void (*ejecutame)(ListaParametros *);
} s_funcion;

So, i 'll say you any advance.

Hello
you can also implement virtual function in C++.
you give some definition of function in the base class and declare it virtual and then give another defintion with/without the same signature in the child class.
This excludes static binding and the function relevant to the data would be called dynamically at runtime. But it does seem a litttle bloated.
I would have a look at the C++ reflection library . Seems interesting though.
Regards.