C++ execute function from memory
assembly, c++, inline-assembly
Solution
This certainly can be done.
The biggest part will be the `compile` function, which unless your ".sc" language is VERY trivial will require quite a bit of work. You may want to have a look at for example `llvm`, which allows you to generate code from an intermediate virtual machine instruction set. It adds a lot of code, but makes your life a bit easier when it comes to generating (reasonably good) instructions.
You can't really push arguments in a function - the pushing will be removed when you return. You would have to generate the push instructions as part of the "compile" process.
And you should be able to to do:
int ret = memexec(binary);
You probably want to write `memexec` in assembler, and perhaps have it take multiple arguments (but you'd still have the problem if what type those arguments are, so some sort of list of arguments with type information is probably really what is required - or always pass arguments as strings, or some such)
Assuming you have an operating system made in the last 15-20 years, you will also need to allocate memory with "execute rights", which requires something other than `malloc`. Deopending on OS, the calls you need will vary.
Problem
I recently thought about precompilable scripting language, which would be translated to machine code during program loading. Lets say that I can generate this binary function myself. Now I need to somehow execute it. The general scheme would look like that: ``` char* binary = compile("script.sc"); pushArgsToStack(1,7); memexec(binary); int ret = getEax(); ``` Is there any chance to get it working? Also, would calling jmp to c++ funcion address work like planned? I mean, after pushing args, returnAddr and so on, I want to somehow call that function from my compiled script. Thanks for any answers