Wrappers for C API in programming languages

215 views Asked by At

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:

  1. 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.
  2. 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?
  3. What if the host language runs on a Virtual Machine? The Instruction Set would be different in that case, right?
1

There are 1 answers

0
Marcin On BEST ANSWER

Because it should also compile the foreign language as well.

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.

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?

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.

What if the host language runs on a Virtual Machine? The Instruction Set would be different in that case, right?

The VM has to have the appropriate facilities to load compiled object code.