【问题标题】:boost::asio::write UNICODEboost::asio::write UNICODE
【发布时间】:2012-01-08 08:37:55
【问题描述】:

我在 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()?

【问题讨论】:

  • 您的代码只使用了宽字符type。这(大部分)与字符 encodings... 正交

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


【解决方案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

【讨论】:

    【解决方案2】:

    您需要知道您的数据是以什么编码形式传入的。

    例如,在我的应用程序中,我知道 unicode 数据以 UTF-8 格式输入,因此我使用函数的普通 char 版本。然后我需要将缓冲区视为 unicode utf-8 数据 - 但一切都可以接收/发送。

    如果您使用不同的字符编码,那么您可能(也可能不会)像您尝试过的那样使用宽字符版本获得更好的里程数。

    【讨论】:

    • 如果我收到 UTF-8 中的 Unicode,我不会丢失任何字符吗?如果没有,使用 wI/O 函数有什么好处吗?
    • @Takashi-kun 如果您使用的是 UTF-8,那么使用宽字符版本没有优势,而且有很多劣势。 UTF-8 是一种基于 8 位 (char) 的编码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-18
    • 1970-01-01
    • 2018-05-02
    • 2013-01-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多