How do I send an ICU UnicodeString using a boost::asio:write call?
I'm curre开发者_高级运维ntly using the ICU library to handle Unicode data, and am trying to send a UnicodeString
over a socket. Currently looking at the example using a basic time server:
Daytime.3 - An asynchronous TCP daytime server
boost::asio::async_write(socket_, boost::asio::buffer(message_),
boost::bind(&tcp_connection::handle_write, shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred)
);
Now, I've looked over various function signatures and it looks as though boost::asio::buffer
can take a boost::asio::const_buffer
, but I'm not sure on how the conversion to it works given a UnicodeString
. How should I go about converting to const_buffer
, or is there another way I should be going about doing this? Thank you ahead of time for all responses.
Assuming you want to send the data using UnicodeString
's default internal encoding (instead of forcing e.g. UTF-8 or UTF-32), then the following should work:
// given UnicodeString ustr
boost::asio::const_buffer(ustr.getBuffer(), ustr.length() * sizeof(UChar));
See UnicodeString::getBuffer() and UnicodeString::length() for more information.
EDIT (in response to comment): To send normalized UTF-32 data, try something like this (adding error handling and extending object lifetime as necessary):
UErrorCode err = U_ZERO_ERROR;
int32_t const size = ustr.toUTF32(0, 0, err);
err = U_ZERO_ERROR;
std::vector<UChar32> databuf(size);
ustr.toUTF32(&databuf[0], size, err);
boost::asio::const_buffer(&databuf[0], databuf.size() * sizeof(UChar32));
精彩评论