Ok so I've used function pointers for some time. I was trying to figure out if this was possible.
First. It IS possible to convert a function pointer into an array of bytes.
It is also possible to reconstruct that function with the bytes in that array.
I would like to save a function into an array of bytes, and lets say save it to a text file (func.dat). Then later read that text file and execute the particular function...
Is it possible? It seems it should be possible the only problem I run across is finding the size of the array that makes up the function.
Is there any way to do this?
int func()
{
return 1+1;
}
int main()
{
int (*foo)() = func;
char* data = (char*)func;
// write all the data
char* copyFunc = new char[sizeof(func)];
for(int i = 0; i < sizeof(func); i++)
copyFunc[i] = data[i];
int (*constructedFoo)() = (int (*)())copyFunc;
return 0;
}
of course this code won't compile because sizeof does not work for functions, does anyone know how to get the size of a function? Or the size of the function header/footer.
I have tried things like
int func()
{
1+1;
new char('}');
}
Then searched for the } char (as the end of the function) but that size doesn't work.
If your wondering why I need it, it could be used for lets say, sending a function to a remote computer to execute (thinking of parallel processing) Or even saving a function in a file like in my first example to later be used, this can be helpful.
Any help is greatly appreciated.