Answer the question
In order to leave comments, you need to log in
How to compile a function into executable code without "links"?
There was a tricky problem which never faced. Let's say we have a code:
int test()
{
HMODULE user32;
int (*msgbox)(HWND hWnd, LPCTSTR lpText, LPCTSTR lpCaption, UINT uType);
user32 = LoadLibrary("user32.dll");
msgbox = (int (__cdecl *)(struct HWND__ *,const char *,const char *,unsigned int )) GetProcAddress(user32, "MessageBoxA");
msgbox(0, "MSG", "Header", 0);
FreeLibrary(user32);
return 0;
}
Answer the question
In order to leave comments, you need to log in
I did not fully understand what you want to do, but what you describe is very similar to a dynamic library. Why doesn't she suit you?
You can get your function as a set of bytes, given the address of the beginning and end of the function. The first one is simple. But the second ... I don’t know any “honest” ways to get it. But you can, for example, knowing the address of the beginning of the function, start reading it and try to find its epilogue. But here, as always in C++, you need to be careful. The epilogue may depend on the compiler, its settings and platform. Yes, and the function itself can be inlined, call other functions that will not be available after "copying" and other delights.
You can also look here:
stackoverflow.com/questions/4156585/how-to-get-the...
If, judging by the comments, you have the task of loading and executing code from outside,
then just type in Google - how to write c ++ plugin system
and you will get excellent articles with drdobbs and a million more links.
Simple enough with the code here www.cplusplus.com/articles/48TbqMoL
And you are rightly told that this is a dll, and LoadLibrary is your friend and partner.
Articles about how best to make a plugin system are better to read - don't step on a bunch of rakes.
If you do stupidly as you wrote, the application can stupidly fall. If you do not want to make your own compiler, then do not try to shove your code into memory and execute it. If you want your own scripting engine with a JIT compiler, then dig in the direction of JIT compilers.
What you described looks a lot like linux kernel modules, which are essentially ordinary object files that, when loaded into the kernel, go through the linking stage. You can start looking from there.
True, I have a fear that it is generally possible to do this in user space without any very dirty hacks, anyway, whatever one may say, and the execution of arbitrary code is considered a hole in the security of the system. But I'm not a real welder, so I could be wrong.
To get an object file, gcc and clang have the -c option. VS should also have something like this, but I don’t have VS, so I can’t look at it. Try running cc1{something}.exe with /? - He'll probably say.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question