Re: [Newbie Alert] How can I interface an interpreter to C code? (Anton Ertl)
24 Dec 2005 15:35:06 -0500

          From comp.compilers

Related articles
[Newbie Alert] How can I interface an interpreter to C code? (Ravi Mohan) (2005-12-23)
Re: [Newbie Alert] How can I interface an interpreter to C code? (2005-12-24)
| List of all articles for this month |

From: (Anton Ertl)
Newsgroups: comp.compilers
Date: 24 Dec 2005 15:35:06 -0500
Organization: Institut fuer Computersprachen, Technische Universitaet Wien
References: 05-12-063
Keywords: C, interpreter
Posted-Date: 24 Dec 2005 15:35:06 EST

"Ravi Mohan" <> writes:
>I now wish to learn how to interface c code to the languages I create.
>In other words, I would like to call existing C libraries from the
>languages I create.
>I am utterly at a loss how to do this. Can someone please point me at
>any book or website that explains how to interface existing C code to
>an interpreter/bytecode based vm?

There are two libraries for doing the actual calling and stuff:

- ffcall <>, which is
    documented, simpler and a little faster.

- libffi, where the latest versions are distributed with gcc and are
    pretty much undocumented; it is also slower and more complex. On
    the plus side, when you debug programs that call through libffi, the
    backtrace works (it does not with ffcall).

It is probably a good idea to look at examples of their use. One such
example is in the Cacao JVM interpreter:

Look at the function nativecall() (towards the end of the file). This
example contains support for both ffcall and libffi (call only, no
callbacks or other advanced features).

In addition, you will probably want to use dlopen() and dlsym() to get
the addresses of the functions you want to call.

>From what I understand from a survey of various languages with ffi,
>the first step would seem to be to write a vm/interpreter *in C*

That is not necessary, but the libraries above have C interfaces, so
you need to be able to at least call C from your implementation
language. Many people write VM interpreters in C (or in languages
that compile to C, like Vmgen), though, because C (especially with the
GNU C extensions) is quite good for the task.

>then have some kind of "mylanguage.h" header file that exposes various
>data structures of the VM/AST.

Such a header file is useful if the C code (whether it is the callee
of the interpreter or the caller) should be able to access these
structures. It is not necessary if you just want to call C-library

- anton
M. Anton Ertl

Post a followup to this message

Return to the comp.compilers page.
Search the comp.compilers archives again.