Dynamically creating functions in C

Viewed 16142

How can I dynamically create a function in C?

I try to summarize my C problem as follows:

  • I have a matrix and I want to be able to use some function to generate its elements.

  • function has no arguments

Hence I define the following:

typedef double(function)(unsigned int,unsigned int);

/* writes f(x,y) to each element x,y of the matrix*/
void apply(double ** matrix, function * f);

Now I need to generate constant functions within the code. I thought about creating a nested function and returning its pointer, but GCC manual (which allows nested functions) says:

"If you try to call the nested function through its address after the containing function has exited, all hell will break loose."

which I would kind of expect from this code...

function * createConstantFunction(const double value){
 double function(unsigned int,unsigned int){
   return value;
 }
 return &function;
}

So how can I get it to work?

Thanks!

10 Answers
Related