opensourcerouting / c-capnproto

C library/compiler for the Cap'n Proto serialization/RPC protocol
MIT License
118 stars 40 forks source link

Example to add "Data" type data #18

Closed blowfish2003 closed 7 years ago

blowfish2003 commented 7 years ago

Hi,

Thanks for the C implementation of capnproto.

I have hit a wall with regard to using a "Data" type for serializing. De-serialization works well but I am not able to serialize and send data using any method.

Can you please give a simple example to serialize the following structure struct DataMessage { packetdata @0 :Data; }

Thank you very much in advance

eqvinox commented 7 years ago
@0xed2b3b98b3eb515b;
struct Msg {
    data @0: Data;
}
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <assert.h>
#include <unistd.h>

#include "data.capnp.h"

int main(int argc, char **argv)
{
    uint8_t data[] = { 0x12, 0x34, 0x00, 0x56, 0x78 };

    /* create capn + capn segment */
    struct capn c;
    capn_init_malloc(&c);
    capn_ptr cr = capn_root(&c);
    struct capn_segment *cs = cr.seg;

    struct Msg msg;

    /* capn_list8 & capn_data are essentially the same (they both just contain a single capn_ptr)
     * usage is slightly convoluted sadly */
    capn_list8 list8 = capn_new_list8(cs, sizeof(data));
    capn_setv8(list8, 0, data, sizeof(data));
    msg.data.p = list8.p;

    /* encode & set as root */
    Msg_ptr pp = new_Msg(cs);
    write_Msg(&msg, pp);
    assert(capn_setp(capn_root(&c), 0, pp.p) == 0);

    uint8_t obuf[4096];
    size_t sz = capn_write_mem(&c, obuf, sizeof(obuf), 0);
    capn_free(&c);

    write(1, obuf, sz);
    return 0;
}
$ ./datatest | capnp decode data.capnp Msg
(data = "\x124\x00Vx")
blowfish2003 commented 7 years ago

Thanks a lot equinox. The "capn_list8" part is the one I totally missed. I will make modifications and post the results.

eqvinox commented 7 years ago

Added note in header, don't have a better place for documentation currently. -- closing