说这样的结构:
typedef struct testVertex_s {
char *vert_name; //for test only...
float x;
float y;
float z;
}testvertex_t;
Run Code Online (Sandbox Code Playgroud)
如何使用python将其写入二进制文件?我想用c中的fread读它;
为什么必须是二进制?文本是微不足道的,并且更容易与之交互.
如果你真的想要二进制文件,请使用struct模块.确保定义字节顺序,并阅读每场分别在C,也不会尝试做一个fread()成一个C结构.
你可以像这样打包:
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))
Run Code Online (Sandbox Code Playgroud)
这将字符串写为普通的以0结尾的字符串,紧接着是浮点数.上面得到的数据是"hello\x00\xc3\xf5H@\xa4p<B\x00\x00\x88A"(表示为Python字符串文字).
对于这种情况,您将需要动态分配当然的字符串,这应该是显而易见的.