c++cffilanguage-implementationlanguage-binding

Creating FFI between C and my language


Let's say that I have implemented a programming language, (we'll call it A for now). A is pretty similiar to C.

I want my users to be able to access functions and data structures from already-existing C libraries. Is this possible? If it is, how would a naive implementation look ?

A


Solution

  • This largely depends on what sort of language A is.

    If it is a compiled language, then you need to produce appropriate assembler code (look up "calling conventions", particularly the C calling convention) to call the appropriate C function. If you're using LLVM, you can do this fairly easily by using the declare and call statements. After you've done that, you'll need to link the executable against the C library in question.

    If it is an interpreted language, however, then you'll need to dynamically load the library. How you do this is platform-specific: for instance, on unix-type systems, this can be achieved via the dlopen function.