C++ Saving/Loading a function as bytes. Getting the size of a function
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)() = 开发者_StackOverflow社区(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.
What you're trying to do is not possible in C/C++. First of all, functions may not be contiguous in memory in the binary. So there's no definite "size".
Secondly, you can't just load it into another program and execute it because it will violate memory protection (among other things, like address space).
Lastly (if you managed to get this far), all non-relative jumps and references in the function will likely be broken.
EDIT:
The way to go about sending code to remote computers is to send entire (compiled) binaries. Then have the local and remote machines communicate.
Well there is actually a way how to save and load bytes of code and even run them. This is a great arcicle about that:
http://www.codeproject.com/KB/tips/Self-generating-code.aspx?msg=2633508#xx2633508xx
One thing you can do if you want dynamically loaded functions:
Create a dynamic library containing your functions (
.dll
or.so
)Export those symbols with
extern "C"
and if necessarydeclspec(dllexport)
Load the library at runtime with
LoadLibrary()
ordlopen()
Extract a particular symbol with
GetProcAddress()
ordlsym()
Execute it with
libffi
.Clean up after yourself with
FreeLibrary()
ordlclose()
精彩评论