0

我想编写一个序列化器应用程序,它将任何类型的 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 打包成消息包格式?

4

0 回答 0