[erlang-questions] Passing binary strings to c port

Michael Santos michael.santos@REDACTED
Mon Jun 6 17:32:15 CEST 2011


On Mon, Jun 06, 2011 at 04:10:09PM +0100, Dave Challis wrote:
> I've got an erlang program which uses binary strings (e.g.
> <<"abc">>), and a c port with some functions which operate on char
> arrays.
> 
> Is it safe to pass this binary string directly to c (using
> ei_decode_binary) for use in char arrays?
> 
> Or should I always use binary_to_list(<<"abc">>) before passing it
> to c, then decode using ei_decode_string?
> 
> My main worry is whether binary strings in erlang could contain the
> null character somewhere (e.g. passing <<"abc\0def">> to c port and
> decoding as a binary results in c seeing the string "abc").

Yes, it's safe for NULLs. The external term format puts the length of
the binary in the header:

1> term_to_binary(<<"abc\0def">>).
<<131,109,0,0,0,7,97,98,99,0,100,101,102>>

If you're encoding atoms or strings on the C side and they may contain
NULLs, use the ei_encode_string_len/ei_encode_atom_len functions.



More information about the erlang-questions mailing list