[erlang-questions] best practice for calling C from Erlang
Tue Dec 14 14:59:19 CET 2010
On Mon, Dec 13, 2010 at 1:37 PM, Joe Armstrong <> wrote:
> What is "best practice for calling C from Erlang"
> I have a C library I want to call from Erlang - nothing complicated.
> Mostly the C functions are called with simple types, integers, strings etc.
> and the return value is uninteresting. In the case where the return value
> interesting I mostly require an opaque return value - ie all I might
> ever want to do
> is re-use it in a subsequent call to a different C routine, so the actual
> value need never cross the C/Erlang boundary, but could be passed back
> and forth
> as a reference.
> What is the best (and easiest) way to call this from Erlang.
> Is there any program that takes a file containing C type declarations
> (either in ANSI C, or as a erlang terms) and automatically builds
> the C and Erlang sides of the interface?
> The problem here is not the complexity of an individual
> call, but the fact there are a large number of simple and rather
> boring functions than must be called.
> I know all about the ports
> interface linked-in drivers etc. My question is more to do with
> the automatic generation of an interface from some kind of specification.
In every project I have worked on where an automatic generation of stub code
based on some kind of interface spec was used, it got replaced by
handwritten shims after about 12 - 18 months.
This was always due to the mismatch of levels of abstraction. This leads to
the generator getting adapted, and adapted, and adapted ...
My approach has since then changed to always design an interface layer that
allows for a smooth transition between the levels of abstraction on each
Especially going from Erlang to C (or the other way round) you will quite
likely require some kind of layer that translates between your Erlang API
idioms and those of C. You are probably thinking that doing this completely
on the Erlang side (from some automatically generated C level interface) is
preferred to doing it in C. But you will find that some translations of data
structures is better done at a lower level, whereas others may be easier at
a higher level. Once you have the code generator for your interface, you
will start spending an enormous amount of time tweaking that code generator
to accommodate your translation routines.
If you are in the business of writing such a generator, fine.
If you just want to use some C library, then, usually, not fine.
More information about the erlang-questions