1

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?
nobody
  • 19,814
  • 17
  • 56
  • 77
shar
  • 1,988
  • 2
  • 18
  • 25
  • This is a perfectly reasonable question. – Marcin Dec 12 '14 at 18:26
  • This question is hard to answer, because it's so general. If you're speaking specifically about python and C, then the simple answer is 'python knows how to lay out parameters on the stack and jump to memory that represents a compiled C function'. but a lot of the answers that shar is looking for are very implementation specific. – Woodrow Douglass Dec 12 '14 at 18:36
  • Atleast pointing to some good resources on this topic would help me a lot in understanding – shar Dec 12 '14 at 18:38

1 Answers1

3

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.

Marcin
  • 48,559
  • 18
  • 128
  • 201