Is it possible to create a function dynamically, during runtime in C++?
Solution 1:
Yes, of course, without any tools mentioned in the other answers, but simply using the C++ compiler.
just follow these steps from within your C++ program (on linux, but must be similar on other OS)
- write a C++ program into a file (e.g. in /tmp/prog.cc), using an
ofstream
- compile the program via
system("c++ /tmp/prog.cc -o /tmp/prog.so -shared -fPIC");
- load the program dynamically, e.g. using
dlopen()
Solution 2:
You can also just give the bytecode directly to a function and just pass it casted as the function type as demonstrated below.
e.g.
byte[3] func = { 0x90, 0x0f, 0x1 }
*reinterpret_cast<void**>(&func)()
Solution 3:
Yes, JIT compilers do it all the time. They allocate a piece of memory that has been given special execution rights by the OS, then fill it with code and cast the pointer to a function pointer and execute it. Pretty simple.
EDIT: Here's an example on how to do it in Linux: http://burnttoys.blogspot.de/2011/04/how-to-allocate-executable-memory-on.html