Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function pointer call when signature is given only at runtime

Consider the following situation:

You are given the pointer to a function as a raw pointer

void * function_pointer;

and the arguments to be passed to the function are available as a vector of a union type.

union Types {
  void   *ptr;
  float  *ptr_float;
  double *ptr_double;
  float  fl;
  int    in;
  double db;
  bool   bl;
};

std::vector<Types> arguments;

Thus, the functions' signature is only available in program state (as opposed to be known at compile time)

What would be the recommended way (C++ 11) to make this call ?

It would be possible to alter the arguments vector to something like this:

std::vector< std::pair<int,Types> > arguments;

where the first element of the pair would clearly identify of which type the argument is.

Technically, the signature is only given in the second form. Because only in the first form you can't tell what's the signature like.

like image 605
ritter Avatar asked Oct 03 '22 15:10

ritter


1 Answers

In standard C, you must know the signature of a function (at compile time) in order to call it. Calling a function that is of one signature with a function pointer declared of the wrong signature will lead to undefined behavior.

There are libraries that use system-dependent assembly to construct function calls at runtime, like libffi.

like image 158
newacct Avatar answered Oct 19 '22 13:10

newacct