I'm learning to build an OOP language that can be compiled to bytecode, then interpret it using stack based vm implemented in c++. My problem is how to call the native function (in my case is C++ function) in my own language.
For example, I have a c++ file: native.cpp
float div2(int x) {
return float(x) / 2;
}
and func call in my language:
import native
void main() {
int foo = 1234;
print(native.div2(foo));
}
If I create a new instruction, I must re-build the whole interpreter.
Sorry, my English is not good.
Assuming the question is about how to add function calls to your OOP language without having to write a bunch of use-case-specific support code to your interpreter every time you add another native function... one way to do it would be to write a generalized function-calling interface with native functions registered by name. For example, your C++ file could include a std::map that (at initialization-time) is populated with the names of the various functions that the OOP language is allowed to call, e.g.:
std::map<std::string, std::function> userAccessibleFunctions;
int main(int argc, char ** argv)
{
userAccessibleFunctions["div2"] = div2;
[... add other functions here...]
// the rest of your program's startup-and-run code here
}
... then when your OOP language needs to call a native function, it can look up the function by its name in the userAccessibleFunctions table, and if it exists, it can call it. (Note that I'm not including info on how to handle different argument types and return types here, since I haven't used std::function enough to speak about that with confidence)