[erlang-questions] Strings, buffers and FFI calls

Alceste Scalas alceste@REDACTED
Wed Sep 12 09:21:45 CEST 2007


Il giorno mar, 11/09/2007 alle 18.11 +0200, Claes Wikstrom ha scritto:
> Alceste Scalas wrote:
> > 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})
> 
> ok -  a bit ugly - but ok.

Well, thinking more about it, it's ugly enough to be avoided whenever
possible --- and since strings and buffers are quite a common return
type, some support should definitely exist.

Here are some ideas (their implementation would be trivial):

'cstring' type for FFI calls:
      * when used for function arguments, it would work like 'pointer';
      * when used as function return type, it would cause the FFI call
        to return a {StringBin, StringPtr} tuple, where:
              * StringBin is a binary() containing a *copy* of the
                string (with the trailing \0);
              * StringPtr is an integer with the string pointer (as
                returned by the C call).

These two auxiliary BIFs could also be very useful:
      * ffi:cstring_to_binary(StringPtr) would return a new binary()
        with a copy of the given NULL-terminated string (including the
        trailing \0);
      * ffi:pointer_to_binary(Pointer, Size) would return a new binary()
        with a copy of Size bytes read from Pointer.

These additions would give an easier and functional interface for
handling strings and buffers --- but at the same time, the original
pointers would be available when needed.

What do you think?

Regards,

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




More information about the erlang-questions mailing list