boost::asio::write UNICODE

3

我有以下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()?

3
您的代码仅使用宽字符类型。这(大多数情况下)与字符编码是正交的…… - ildjarn
2个回答

3
你需要知道你的数据是以哪种编码方式传输的。
例如,在我的应用程序中,我知道Unicode数据是以UTF-8的方式传输的,所以我使用普通的 char 版本函数。然后,我需要将缓冲区视为Unicode UTF-8数据 - 但一切都能正常收发。
如果你正在使用不同的字符编码方式,则可能(或可能不会)通过使用宽字符版本获得更好的效果,就像你尝试过的那样。

如果我以UTF-8格式接收Unicode,我不会失去任何字符吗?如果不是,使用wI/O函数有什么优势? - Ivan Santos
@Takashi-kun 如果你正在使用UTF-8,那么使用宽字符版本没有任何优势,反而有很多缺点。UTF-8是一种基于8位(char)的编码。 - Michael Anderson

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接