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.
1 Answer
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".
-
1This is correct for C functions. C++ classes are way harder. For starters, they usually contain multiple member functions, including special member functions (constructor/destructor) with different semantics. Classes can also contain static data members. Typical C++ implementations have a special static data member, a "vtable" for virtual functions.– MSaltersOct 3 at 11:25
-
BTW, parsing C++ headers isn't hard. You just outsource it to
clang
. Trying to do that yourself is utterly hopeless. The type system in C++ is very much Turing-complete; you need to be able to interpret everyconstexpr
function. Without that, you can't even determine what functions are declared in a header.– MSaltersOct 3 at 11:34 -
1Yeah, correctly implementing the C++ virtual dispatch is likely to be miserable - one approach that I'm sure I've seen is emitting or requiring a "wrapper" layer which is in C++ but exports an "extern C" interface, and handles calling new()/delete() and boxing up C++ objects. Or you could try COM.– pjc50Oct 3 at 12:29
-