How can I dynamically create a function?

c, dynamic, function

Solution

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.

Problem

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?

Original source

Related problems