Search code examples
c++boostboost-asio

How to create an boost::asio::ip::address_v6 from sockaddr_in6 without making an extra copy?


The problem is that address_v6 class accepts raw data strictly as bytes_type class:

typedef array< unsigned char, 16 > bytes_type;

but sockaddr_in6 struct doesn't have that, it has C-style arrays, that can't be converted to std::array without copying. So I have to create an std::array, copy data there, and pass that array to address_v6, which copies data from that std::array to its internal buffer.

I wish I could use or implement some C-style array viewer class but I wouldn't be able to pass it to the constructor anyway, because it's not a template function.

Is there some way to create an address_v6 without making an extra copy of the data?


Solution

  • The std::array is required to be struct that contains raw array as its first and only non-static data member. As the raw array contains unsigned chars it is therefore standard layout class. So I can not find a reason from standard why following code would not work:

    auto& bytearray = reinterpret_cast<std::array<unsigned char,16>&>(ipv6socket->sin6_addr.s6_addr); 
    

    Replace auto& with plain auto if you want to copy.