[erlang-questions] Passing data between Erlang and C port while preserving padding and alignment?

Richard O'Keefe raoknz@REDACTED
Sun Dec 9 12:46:51 CET 2018


The alignment/padding in a C struct depends on the hardware, the ABI, the
compiler, and the options that were given to the compiler at build time.
In the past I ran into serious problems trying to exchange binary data
between C programs running on the same machine that were compiled by
different compilers.  (I have three C compilers on my el-cheapo Linux box,
and could easily add a fourth if I wanted, all free.  The last time I tried
the fifth free compiler, it did not work, but I live in hope.)

Me, I'd use an existing C compiler to do the parsing, such as GCC-XML or
CastXML, extract the struct declaration from that, and generate both C and
Erlang code for pickling and unpickling.  (Or if you are fluent in SML, you
could give the ckit library a go.  There are also C
lexers/parsers/verifiers in OCaml.)

More likely, I'd just invent a little tabular DSL for describing the
structs I wanted to communicate between C and Erlang, and generate the C
declaration and other code and the Erlang code from that, to save having to
learn yet another tool.


On Fri, 7 Dec 2018 at 17:21, Frank Muller <frank.muller.erl@REDACTED>
wrote:

> Hi guys
>
> Let assume the following C structure (I have a bunch of them, all
> different):
>
> struct foo {
>  int32 i32;
>  char c;
>  int64 i64;
>  char * p;
>  float f;
>  char * str[16];
> };
>
> When it gets compiled, GCC will add some padding to align data types (i.e
> self-alignment). More info at:
>
> http://www.catb.org/esr/structure-packing/
>
> On the Erlang side, it is very easy to generate a binary which matches
> this C structure field by field.
> But it won’t work because of the padding :-/
>
> Question: how can I derive the GCC's padding, and automatically add it to
> my Erlang binary?
>
> I am open to any generic/flexible solutions even if I have to
> auto-generate these C structures (i.e meta-programming).
>
> Thank you.
> /Frank
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20181210/7f82fd39/attachment.htm>


More information about the erlang-questions mailing list