我想编写一个序列化程序应用程序,它将任何类型的C数据结构编码为MessagePack格式。我见过的所有例子都显示了已知结构的编码,例如使用MPack:
// encode to memory buffer
char* data;
size_t size;
mpack_writer_t writer;
mpack_writer_init_growable(&writer, &data, &size);
// write the example on the msgpack homepage
mpack_start_map(&writer, 2);
mpack_write_cstr(&writer, "compact");
mpack_write_bool(&writer, true);
mpack_write_cstr(&writer, "schema");
mpack_write_uint(&writer, 0);
mpack_finish_map(&writer);
// finish writing
if (mpack_writer_destroy(&writer) != mpack_ok) {
fprintf(stderr, "An error occurred encoding the data!\n");
return;
}
// use the data
do_something_with_data(data, size);
free(data);
但我想要的是能够编码任何C数据结构。例如,如果我有以下内容:
struct My_Struct{
int number1;
float number2;
char array[6];
};
struct My_Struct ms = {10, 4.44, "Hello"};
以编程方式,我怎么知道前4个字节代表一个int,这样我就可以调用一个mpack_write_int函数来开始将int打包成一个messagepack格式?