boost :: asio ::写UNICODE

时间:2011-11-28 22:40:15

标签: c++ boost unicode stream boost-asio

我在ANSII中有以下代码:

boost::asio::streambuf buffer;
std::ostream oss(&buffer);

boost::asio::async_write(socket_, buffer,
    strand_.wrap(
    boost::bind(&Connection::handleWrite, shared_from_this(),
    boost::asio::placeholders::error)));

我需要将其转换为UNICODE。我尝试了以下方法:

boost::asio::basic_streambuf<std::allocator<wchar_t>> buffer; 
std::wostream oss(&buffer); 

boost::asio::async_write(socket_, buffer,
    strand_.wrap(
    boost::bind(&Connection::handleWrite, shared_from_this(),
    boost::asio::placeholders::error)));

有没有办法在UNICODE中使用async_write()?

2 个答案:

答案 0 :(得分:3)

您需要知道数据的编码格式。

例如在我的应用程序中,我知道unicode数据是以UTF-8形式出现的,因此我使用了函数的正常char版本。然后我需要将缓冲区视为unicode utf-8数据 - 但是一切都被接收/发送好了。

如果您正在使用不同的字符编码,那么您可能(或可能不会)使用您尝试过的宽字符版本来获得更好的语言。

答案 1 :(得分:1)

我并不是你在这里打的所有电话(最近我自己刚刚深入了解asio),但我知道你可以简单地用矢量处理数据。

因此,例如,这是我为读取unicode文件并通过posix套接字传输所做的:

// Open the file
std::ifstream is(filename, std::ios::binary);

std::vector<wchar_t> buffer;

// Get the file byte length
long start = is.tellg();
is.seekg(0, std::ios::end);
long end = is.tellg();
is.seekg(0, std::ios::beg);

// Resize the vector to the file length
buffer.resize((end-start)/sizeof(wchar_t));
is.read((char*)&buffer[0], end-start);

// Write the vector to the pipe
boost::asio::async_write(output, boost::asio::buffer(buffer),
                         boost::bind(&FileToPipe::handleWrite, this));

此处记录了对boost :: asio :: buffer(vector)的调用:http://www.boost.org/doc/libs/1_40_0/doc/html/boost_asio/reference/buffer/overload17.html