In some of the LLVM tutorials I’m seen where it’s fairly easy to bind C function into a custom language based on LLVM. LLVM hands the programmer a pointer to the function that can be then be mixed in with the code being generated by LLVM.
What’s the best method to do this with C++ libraries. Let’s say I have a fairly complex library like Qt or Boost that I want to bind to my custom language. Do I need to create a stub library (like Python or Lua require), or does LLVM offer some sort of foreign function interface (FFI)?
In my LLVM code, I create
extern "C"wrapper functions for this, and insert LLVM function declarations into the module in order to call them. Then, a good way to make LLVM know about the functions is not to let it usedlopenand search for the function name in the executing binary (this is a pain in the ass, since the function names need to be in the.dynsymsection, and it is slow too), but to do the mapping manually, using ExecutionEngine::addGlobalMapping.Just get the
llvm::Function*of that declaration and the address of the function as given in C++ by&functionnameconverted tovoid*and pass these two things along to LLVM. The JIT executing your stuff will then know where to find the function.For example, if you wanted to wrap
QStringyou could create several functions that create, destroy and call functions of such an objectAnd create proper declarations and a mapping. Then you can
callthese functions, passing along a memory region suitably aligned and sized forQString(possiblyalloca‘ed) and ai8*pointing to the C string data for initialization.