Alex Rivera | Logout

How can I dynamically create a function?

Asked 2009-12-03T13:50:17.523
18

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;
}

How can I get it to work?

Edit
Report

2 Answers

24

C is a compiled language. You can't create code at run-time "in C"; there is no specific C support to emit instructions to memory and so on. You can of course try just allocating memory, making sure it's executable, and emit raw machine code there. Then call it from C using a suitable function pointer.

You won't get any help from the language itself though, this is just like generating code and calling it in BASIC on an old 8-bit machine.

answered 2009-12-03T13:58:03.067
2

As unwind already mentioned, "creating code at runtime" is not supported by the language and will be a lot of work.

I haven't used it myself, but one of my co-workers swears by Lua, an "embedded language". There is a Lua C API which will (theoretically, at least) allow you to perform dynamic (scripted) operations.

Of course, the downside would be that the end user may need some sort of training in Lua.

It may be a dumb question, but why does the function have to be generated within your application? Similarly what advantage does the end-user get from generating the function themselves (as opposed to selecting from one or more predefined functions that you provide)?

answered 2009-12-03T14:16:15.063

Your Answer