can I do something like:
typedef void (*functor)(void* param);
//machine code of function
char functionBody[] = {
0xff,0x43,0xBC,0xC0,0开发者_StackOverflowxDE,....
}
//cast pointer to function
functor myFunc = (functor)functionBody;
//call to functor
myFunc(param);
Formally, the C language doesn't allow conversions between function pointers and object pointers, so this can't be done.
However, many C implementations - perhaps even "most" - support this as an extension. Whether it works or not depends on things like memory permissions and cache coherency, which will change depending on your architecture and operating system.
Depends on protection ring.
on most popular desktop platforms, you will not be able to execute code in data segment
because of page privileges.
On modern operating systems, it depends on whether the memory is marked executable or not. On POSIX systems, it may be possible to obtain executable memory using mmap
. Keep in mind that even on a given cpu architecture, calling convention may vary. For example if the caller expects the callee to clear arguments off the stack, your code had better do that or it will crash on return. (Normally, C ABIs don't make this stupid requirement, but it's something to think about.)
Rather than trying to call your machine code directly as a C function pointer, it may be better to write an inline asm wrapper that calls it. This way, you have control over the calling convention.
It could work. Possibly using const char[] for the machine instructions is even better, because on many platforms static const storage is placed in the read-only program memory section.
精彩评论