-
Is This Possible?
Hi, I'm wondering if it would be possible to have a prompt from a program and actually call functions inside the program at run-time without using string comparison and stuff (or maybe just a little).
Example:
> Function(paramaterValue);
This would theoretically execute this function and parse the given parameter.
The only way I can think of this working (and this is a complete guess, I've not really worked with inline ASM before) would be to use some inline ASM. Since everything gets converted to ASM at compile, theoretically the loop would need to read the string, parse it, extract the parameter(s) and treat these as parameters with some inline ASM by pushing them to the stack for the upcoming function call.
Although, another dilemma, say what I've said so far is possible, how would I convert the Function's name (which will be in a user-inputted string format) into the actual address of the function? (or could I somehow use the name - although I doubt this as a possibility).
Anyway once that is done I'm presuming the inline ASM would be required to jmp to the address of the function (and possibly pop the parameters from the stack? Would the function handle this?)
I just think this would be a cool thing to code for learning purposes (and possibly even debugging purposes).
Let me know what you think, thanks!
-
Well something will end up doing a string comparison of some sort, even if you don't.
Somewhere along the line, you take your function name string, and perform a lookup to return a function pointer.
I suppose you could hash the function name, and return (hopefully) a unique bucket ID where the function pointer is stored, but it still amounts to the same thing.
-
Thanks for the reply, I take it no one else has something to add? lol. And yeah I guess it would be possible using function pointers, never really thought of that :).
-
If you really want power and flexibility you could even pick up an off-the-shelf scripting solution like Lua, which easily allows you to bind Lua variables to your C functions. However, parameter passing requires a fair amount of checking on your part to make sure the proper variables of the proper types were pushed onto the Lua stack.
There's also the benefit that Lua is very easily sandboxed using just Lua commands, so you can hide as much of Lua's built-in functionality from your user as you want (for example, getting rid of io.* to disable file access.)
-
With some macro trickery it's possible to build a list of strings and their related function pointers, for each one that uses the macro around its declaration. Check out some unit test frameworks.