[erlang-questions] FFI for Erlang: patches and draft EEP

Alceste Scalas alceste@REDACTED
Tue Sep 11 17:46:35 CEST 2007


Il giorno mar, 11/09/2007 alle 17.12 +0200, Claes Wikstrom ha scritto:
> Alceste Scalas wrote:
> > The current FFI implementation, taken alone, does *not* allow the
> > C side to fiddle with the Erlang VM (e.g. by allocating binaries
> > or other terms).
> 
> My question was that I couldn't find any way for the C code
> to return e.g. a string back to the erlang caller, a string
> on the C side would then typically be represented as a binary()
> on the erlang side.

Well, I considered about adding a "string" type to the ones supported by
the FFI extension.  However, it would introduce some complications with
returned strings: should the string data be copied in a binary?  Or
should the new binary point *directly* to the string data (if possible)?
And in the latter case, how should the allocated memory be freed?  And
if the data is always copied, how to return string data?  Maybe as a
{StringBinary, OriginalPointer} tuple?

In the current FFI implementation, strings are just pointers, and the
caller should know what to do with them.  A binary may be obtained from
a string with a bit of Erlang and side-effects:

        StrPtr = ffi:call(Port, {give_me_a_string}, {pointer}),
        StrLen = ffi:call(Port, {strlen, StrPtr}, {size_t, pointer})+1,
        StrBin = <<0:StrLen>>,
        ffi:call(Port, {strcpy, StrBin, StrPtr},
        {pointer,pointer,pointer})

Then the original StrPtr may be handled as needed.  These 4 lines may be
hidden in the depths of a library binding (so users would never care
about them), and the complications on the FFI side are avoided.

Alternative approaches and suggestions are welcome, of course (no, I
don't like overwriting binaries, either :-)

Regards,

alceste
-- 
Alceste Scalas <alceste@REDACTED>
CRS4 - http://www.crs4.it/




More information about the erlang-questions mailing list