[erlang-questions] FFI: handling refcounted binaries

Martin Bjorklund <>
Fri Sep 14 15:48:50 CEST 2007


Alceste Scalas <> wrote:
> =========================================
> Handling refcounted binaries with the FFI
> =========================================
> 
> Let's suppose that the 'binary' FFI type is added.
> 
> If you just want to *return* a binary (filled with data) from the C
> side, it is easy.  You could just create an ErlDrvBinary in the usual
> way, (erl_driver.h, driver_alloc_binary(), driver_binary_inc_refc()
> etc.).  The FFI would turn it into a "normal" Erlang binary [1].
> 
> If you want to *receive* a handle to an Erlang binary in the form of an
> ErlDrvBinary, and increment/decrement its refcount in order to keep it
> for later use, then:
> 
>   a. if the Erlang binary is still refcounted, it is
>      straightforward [2];
> 
>   b. however, a binary created from Erlang code may *not* be
>      refcounted [3].  In this case, the FFI could force the
>      creation of a refcounted binary, copy the contents
>      of the original one, and pass an ErlDrvBinary to the C
>      side [2].  There, the standard ErlDrvBinary API could be
>      used.

I like this proposal where you always get a ErlDrvBinary.  It's
cleaner than the current driver iovec i/f.



/martin



More information about the erlang-questions mailing list