I came across a feature in some programming languages to call methods in other programming languages. Its called the Foreign Function Interface
. For example, I would be able to call a C Language function inside a Python program. Or I could I write a wrapper for some C library in Python language for other Python users to use those.
One simple example is the ctypes
in Python. So using this, I can access the time
function in libc. I understand to this level. However, I couldn't get a clear picture of how this ctypes itself is implemented and other 'behind the scene' things!
The questions that arise for me here are:
- What kind of features do a compiler for this language require to use the Foreign Function Interface. Because it should also compile the foreign language as well.
- So if the host language is object oriented, and foreign language is not, then I need some kind of mapping to and from objects. How is this handled?
- What if the host language runs on a Virtual Machine? The Instruction Set would be different in that case, right?
No. ctypes, and the like, only need to be able to link to object code. This depends on the target foreign language having appropriate conventions for name mangling inside the object code, which C does.
The C code needs to expose appropriate interfaces for the host language; or equivalently, use some C-language libraries to do so. CPython is written in C, so this is broadly speaking easy in that case.
The VM has to have the appropriate facilities to load compiled object code.