2

I am trying to implement a basic bytecode VM, which I plan to target with a compiler. How can I implement the ability to call external C functions using the bytecode, i.e., call arbitrary functions in runtime. For example, my future compiler should be able to produce programs that call printf(), malloc(), etc. My guess is you could somehow ask the OS for the needed functions address and jump to it, probably making use of things like dlopen() and dlsym(), however I don't know the exact details and the specifics on implementing that in a VM.

1 Answer 1

5

Exactly, you can obtain function pointers via dlsym() and then call them – but how to perform the call depends on the function's calling convention. In theory you could write some assembly to bridge between the languages, but most likely you will want to use libffi. For example, libffi is used by Python's ctypes module in callproc.c.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.