Quantcast

Passing binary strings to c port

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate
star

Passing binary strings to c port

Dave Challis
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").

Thanks,

--
Dave Challis
[hidden email]
_______________________________________________
erlang-questions mailing list
[hidden email]
http://erlang.org/mailman/listinfo/erlang-questions
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate
star

Re: Passing binary strings to c port

Michael Santos-2
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.
_______________________________________________
erlang-questions mailing list
[hidden email]
http://erlang.org/mailman/listinfo/erlang-questions
Loading...