[erlang-questions] best practice for calling C from Erlang
Tue Dec 14 01:27:11 CET 2010
# James Churchman 2010-12-13:
> been wondering myself what the best way to interface D 2.0 is to erlang…. most of the
> usual C ones should would as you can call C (some C++) from D2.0
> i am not sure what the best communication / serialisation mechanism is,
> but given a suitable one..
I don't know D, but BERT format is what other Erlang interfaces use (Java,
Python, erl_interface for C) -- it's pretty simple and convenient, if you're
OK with talking to Erlang node over sockets/pipes.
If you can call D from C too, you could probably wrap you D code into
a builtin port driver or a NIF -- but personally I wouldn't bother unless
someone beat me with a benchmark. The BERT + pipes solution is easy to
debug and keeps things nicely isolated.
> for auto generating if you don't already have a list of all function
> names then you could use ctags (available in macports etc… ) the
> "etags" (eg " etags my_c_file.c ") command will give you just the
> function names and return values, but no arity..
> this might be ok as you could autoproduce a lookup table of function
> pointers in c, and assume the arity is given correct from the erlang
> code (eg from the length of an input array, tuple etc..) and call the
> function pointer with the arty of the supplied message from erlang
> just using a case for aritys upto say 10, otherwise ctags (eg " ctags
> my_c_file.c ") will give a much more verbose output and could be used
> to produce the exact code without function pointers, or even auto
> produce thrift / avro etc.. mappings .
> i know that ctags this is used by text editors and plugins to allow
> the browsing of source.. so hopefully will give suitable quality
Yep, for just a list of function names ctags/etags would probably work fine,
but for both static interface and a more dynamic one like you describe
(function calls built at runtime based on user-supplied specs, presumably
using libffi as backend [*]) you really need full function signature -- and
not just that, sometimes you'd like to dissect nested/chained C structures
and unions, so you'd need to supply specs for that too (but more likely hand
written glue code).
Clang output gives you all that information for free, with the slight caveat
that type aliases that were done with C macros will be visible to you only
in their expanded form (and I think some simple typedefs disappeared that
way too, but I might be wrong on that, it's late night ;-). So autogenerated
code will still be type-correct, but may end up ugly and possibly specific
to some version of C code you're interfacing to.
[*] There used to be an EEP (along with implementation) that work this way...
More information about the erlang-questions