How to add bytes to a capnp::word array?

343 views
Skip to first unread message

Zach La Celle

unread,
Sep 30, 2015, 4:42:25 PM9/30/15
to Cap'n Proto
Suppose I have some other process which reads a CapnProto message from the wire, and passes it to my code.  How can I:

- Put the standard C array full of data into an Array<::capnp::word> array?
- If that's not necessary, what's the best way to read this into a MessageReader (right now I'm using a FlatArrayMessageReader with a ::capnp::word array)


Kenton Varda

unread,
Sep 30, 2015, 5:04:41 PM9/30/15
to Zach La Celle, Cap'n Proto
Hi Zach,

In order to convert a byte array to a word array without copying, you must first ensure that the bytes are aligned -- that is, they start on an 8-byte boundary (or 4-byte for 32-bit systems). If you try to use non-aligned data, you may see crashes or slowness (depending on CPU architecture).

Sometimes you can be sure that your data is aligned by virtue of the context -- for example, arrays allocated by malloc() are aligned. But if you don't know for sure, it's safest to make a copy. You can also check at runtime by converting the pointer into an integer and doing arithmetic.

*If* the bytes are aligned, then you can use reinterpret_cast to convert, like:

    kj::ArrayPtr<capnp::word> words(reinterpret_cast<const byte*>(bytes.begin()), bytes.size() / sizeof(capnp::word));

Alternatively, to make a copy, do:

    auto words = kj::heapArray<capnp::word>(bytes.size() / sizeof(capnp::word));
    memcpy(words.begin(), bytes.begin(), words.asBytes().size());

-Kenton

--
You received this message because you are subscribed to the Google Groups "Cap'n Proto" group.
To unsubscribe from this group and stop receiving emails from it, send an email to capnproto+...@googlegroups.com.
Visit this group at http://groups.google.com/group/capnproto.

Zach La Celle

unread,
Sep 30, 2015, 5:11:29 PM9/30/15
to Cap'n Proto, zlac...@gmail.com
Perfect, that's very helpful.  Thank you!
Reply all
Reply to author
Forward
0 new messages