0

I would like to write a serializer application that will encode any type of C data structure into MessagePack format. All examples I have seen show the encoding of known structures such as this using 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);

But what I would like is to be able to encode any C data structure. For example if I had the following:

struct My_Struct{
  int   number1;
  float number2;
  char array[6];
};

struct My_Struct ms = {10, 4.44, "Hello"};

programatically, how would I know that the first 4 bytes represents an int so that I could call an mpack_write_int function to start packing the int into a messagepack format?

Koi
  • 105
  • 9
  • You need to call write function for each struct member manually. C provides not automation for this. There is one idea though: If you need to write lot of these, you could write these definitions to text files in some format, and then use a scripting language which would generate structure definitions, and encoding/decoding functions for you. These kind of tools might exist already. – user694733 Oct 20 '16 at 13:51
  • @user694733, I understand that I will need to call a write function for an int, float, and char array, but how do I know that ms contains these types to begin with? – Koi Oct 20 '16 at 14:18
  • Only way to know is to inspect structure definition manually. C has no method to enumerate structure at runtime. So you'll need to write encoding function for each structure type separately, for example `void encode_my_struct_with_mpack(mpack_writer_t * writer, struct My_Struct ms) { /* call mpack write functions here */ }` – user694733 Oct 21 '16 at 06:04
  • you can see how it realized in msgpack sources, because msgpack can encode user structures and classes. see examples in `msgpack-c/blob/master/test/object.cpp` and `msgpack-c/blob/master/test/user_class.cpp` – o2gy Oct 21 '16 at 12:31

0 Answers0