Convert C types to Erlang types

Matthias Lang matthias@REDACTED
Sat Dec 7 10:06:44 CET 2002


Paroli, Bernardo writes:
 > I'm make a server socket in Erlang and I send message from C
 > client. The C client send the next message:
 > 
 > typedef struct
 > {
 > 	int first;
 > 	char second;
 > } Message;
 > 
 > char buf[1024];
 > Message*p;
 > p = (Message*) buf;
 > 
 > p->first   = 1567;
 > p->second = 's';
 > 
 > send(s, buf, sizeof(Message), 0);
 > 
 > In the Erlang server I'm receive the next binary message:
 > <<31,6,0,0,115,255,255,255>>
 > 
 > I need convernt this structure to the corresponding C structure. 
 > Exist in Erlang something function to make this conversion?

In general, you can't do that because the C standard alloweds more
than one way of laying out a structure, i.e. the binary message for
the same structure with the same data will vary from compiler to
compiler and machine to machine.

One quick and dirty way to do it is to make a few educated guesses and
manually decode the data. In your example, the guesses are:

   1. You have a little-endian machine
   2. Your compiler pads to 32 bit boundaries

5> <<First:32/little, Second:8, _unused:24>> = <<31,6,0,0,115,255,255,255>>.
<<31,6,0,0,115,255,255,255>>.
6> {First, Second}.                                                             {1567,115}

This is not a very good way to do things. A better way is to define a
protocol between your C code and your Erlang code. The choices are
many, reading the "interoperability guide" is a good place to start:

  http://www.erlang.org/doc/r9b/doc/tutorial/part_frame.html

Matthias



More information about the erlang-questions mailing list