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.

Dani AI

Generated

Short answer for : reading a function's bytes from memory and trying to reuse them elsewhere is possible only in very constrained, same-process experiments. Machine code carries relocations, absolute addresses, literal and global-data references, import stubs and calling-convention assumptions. Modern OS/CPU features (ASLR, DEP/W^X, instruction-cache coherency) and the kinds of issues described make blind byte-copying brittle and nonportable.

Safer, practical approaches (pick the one that fits the deployment model):

  • Register-and-dispatch: send a function identifier and arguments; the receiver looks up a pre-registered function pointer (as suggested).
  • Plugin/shared object: build the function into a .so/.dll, transfer the file, and load it with dlopen/LoadLibrary and dlsym/GetProcAddress (as pointed out). Build with position-independent code and match the ABI.
  • Portable runtime/bytecode: send Lua/Python source, WebAssembly, or serialized bytecode and run in a sandboxed interpreter or VM.
  • Remote build/run: transmit source and compile on the target, or use RPC/task-queue patterns instead of shipping raw machine bytes.

When raw-byte experiments are required inside a single controlled build, make the build assist the process: place the function in its own section and use linker start/stop symbols to get the size; compile as PIC, avoid external references, allocate executable pages (mprotect/VirtualAlloc), copy the bytes, and flush the instruction cache (e.g., __builtin___clear_cache on GCC/Clang). Symbol sizes can also be obtained from the object file (nm, readelf, objdump) or via libelf/libbfd — but relocations must still be fixed.

Security and portability cautions: executing transferred machine code is high-risk. For production distributed or parallel work, prefer signed/shared objects, sandboxing (containers/VMs), or language-level serialization/bytecode. The idea is interesting for learning, but the reliable solutions are dynamic loading, RPC, or a portable bytecode/runtime rather than raw function blobs.

Recommended Answers

All 4 Replies

Not possible in the way you described it. But what you can do is to give functions a text string name that is associated with a function pointer.

struct fns
{
   std::string name;
   int (*fn)(); // function pointer
};

Now you will make an array of the above structures. Then when you need to execute a specific function just search the array by text string name. You can do similar with remote processes. Process1 (P1) sends Process2 (P2) the name of the function to be executed and P2 searches the array for the desired function pointer.

Uhmm... saving a function to a file to be able to call it later from anywhere else... if I'm not mistaken (rethorical), this is called a Dynamic Link Library (DLL) (in Windows) or a Shared Object (SO) (in *nix).

Any way you want to do what you want to do, it will either have to be based on or going through the use of a shared library (.dll or .so) file. So, I suggest you look into that topic.

Ok. Well I'm guessing its not possible unless I compile it before hand basically. Thanks for the feedback.

There is a lot more to it than blindly copying a block of code and expecting it to work. It depends very much on the processor and the instructions being used. For example, a switch statement might have a lookup table somewhere else. It might be using jump vectors for dynamic link library imports that won't necessarily be there. It might have string literals that it is expecting to be at a certain address in the const section. It might be referring to global variables that may not be there or may not be at the expected address.

The worst problem is there might be instructions that use absolute addresses - which will be wrong if you put it at a different address. It might call other functions, how will they work? How will it know what address those are at (assuming they exist at all).

commented: good :) +17
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.