2011-11-28 121 views
3

我在ANSII以下代码:的boost ::支持ASIO ::写UNICODE

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

你只简单使用宽字符_type_。这是(主要)正交的字符_encodings _... – ildjarn

回答

3

你需要知道什么编码的数据来为。

例如在我的应用程序中,我知道unicode数据以UTF-8形式出现,因此我使用正常的char版本的函数。然后我需要将缓冲区视为unicode utf-8数据 - 但所有内容都已收到/发送正常。

如果您使用的是不同的字符编码,那么你可能(或可能不会)使用宽字符版本得到更好的milage像你都试过了。

+0

如果我在UTF-8的Unicode接受,我不会失去任何字符?如果没有,使用wI/O功能有什么优势? – Takashi

+0

@隆坤如果你使用UTF-8的工作也没有优势,使用宽字符版本,以及大量的缺点。 UTF-8是一个基于8位(char)的编码。 –

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

提振调用:: ASIO ::缓冲区(矢量)记录在这里:http://www.boost.org/doc/libs/1_40_0/doc/html/boost_asio/reference/buffer/overload17.html