steave
steave

Reputation: 395

How to write a binary struct using python that can be read in c?

say a struct like this:

typedef struct testVertex_s {
       char *vert_name; //for test only...
       float x;
       float y;
       float z;
}testvertex_t;

how to write that to a binary file use python ? I want to read it using fread in c;

Upvotes: 2

Views: 5518

Answers (1)

unwind
unwind

Reputation: 400079

Why must it be binary? Text is trivial, and much simpler to interact with.

If you really want binary, use the struct module. Make sure to define your endianness, and read each field separately in C, do not try to do a single fread() into a C structure.

You could do the packing like so:

import struct
out = open("myvertex.bin", "wb")
string = "hello"
fmt = "<%usfff" % (1 + len(string))
out.write(struct.pack(fmt, string, 3.14, 47.11, 17))

This writes the string as a plain 0-terminated string, followed immediately by the floats. The resulting data from the above is "hello\x00\xc3\xf5H@\xa4p<B\x00\x00\x88A" (represented as a Python string literal).

For this case, you're going to need to dynamically allocate the string of course, which should be obvious.

Upvotes: 9

Related Questions