I want to pass my message to a (bytes, size)-tuple expecting function.
The messageToFlatArray() function returns an array<word>.
Right now, I've implemented it like this:
> const auto serialized = messageToFlatArray(message);
>
> kj::ArrayPtr<const char> byte_view{
> reinterpret_cast<const char*>(std::begin(serialized)),
> reinterpret_cast<const char*>(std::end(serialized))};
>
> assert(byte_view.size() % sizeof(capnp::word) == 0);
> fn(std::begin(bytes), bytes.size()); // (bytes, size)-tuple
And for the situation where I have bytes and want to read my message
from it, I do the following:
> std::vector<char> in;
> gn(std::back_inserter(in)); // fill with bytes
> assert(in.size() % sizeof(capnp::word) == 0);
>
> const kj::ArrayPtr<const capnp::word> view{
> reinterpret_cast<const capnp::word*>(&(*std::begin(in))),
> reinterpret_cast<const capnp::word*>(&(*std::end(in)))};
>
> capnp::FlatArrayMessageReader message{view};
Now I was wondering if this is safe to do, especially regarding all
those nasty reinterpret casts. I was talking to someone who mentioned
strict aliasing rules and that this may be Undefined Behavior without an
extra copy.
That's the reason I was wondering if this is the most idiomatic way and
especially if this is safe to do.
I also checked the word class's documentation:
>
https://github.com/kentonv/capnproto/blob/d6a45490341521fd9d9eaade5b312488555b57b0/c%2B%2B/src/capnp/common.h#L261-L270
and it does mentions reinterpret casts as a need for accessing the contents.
Cheers,
Daniel