boost::asio::write UNICODE

boost::asio::write UNICODE

本文关键字:UNICODE write asio boost      更新时间:2023-10-16

我在ansi中有以下代码:

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)));

是否有一种方法来使用async_write()在UNICODE?

您需要知道您的数据以什么编码进入。

例如,在我的应用程序中,我知道unicode数据是作为UTF-8输入的,所以我使用正常的char版本的函数。然后我需要将缓冲区视为unicode utf-8数据-但所有内容都可以接收/发送。

如果你使用不同的字符编码,那么你可能(也可能不会)使用宽字符版本得到更好的里程,就像你已经尝试过的。

我不完全了解您在这里进行的所有调用(我自己最近才深入了解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