I'm making an interpreter (currently in python but later I'll remake it in C++) and I wondered how I could use a C/C++ function in my language so when somebody wants to write an extension for my language ex. an OpenGL extension he can bind the functions to my language.
Approaches vary, because it depends how your language works, but the general technique:
- load the native code as a library using e.g. "dlopen()"
- identify the function name (see "C++ name mangling" for C++, this is much easier for C)
- get the pointer to the function (e.g. call dlsym())
- convert the types of your language to types required for the function
- have the interpreter call the function
- convert the return type back
- return to your language
You will need a means of understanding the function signatures of the C++ functions, either by parsing the C++ headers (hard) or annotating it in your language. See C#'s "P/Invoke" mechanism or Pythons "CFFI".