c++ - boost-asio 错误消息使用的编码是什么?

标签 c++ boost boost-system

我正在使用 boost-asio,我想正确处理错误消息。

在这个例子中,我打错了字(1278 而不是 127):

boost::system::error_code ec;
auto address=boost::asio::ip::address::from_string("1278.0.0.1",ec);
if(ec)
{
    auto text=ec.message();
    //Do Something with text but what is its encoding ?
}

我收到一条错误消息,它似乎是在 Windows 1252 中编码的(我使用的是 Windows 7)。 所以看起来编码是操作系统编码。

但是,我找不到任何说明这一事实的文档。

boost asio 中的错误消息是否使用操作系统字符集编码?

最佳答案

在深入研究我的系统上的 boost 之后,我发现包含的 hpp 文件包含一个 ipp 文件,该文件依次调用操作系统函数。如果有错误,在这个阶段只知道错误的代码。

真正的错误信息是在调用message()函数时形成的。

Windows 上的实现调用 FormatMessageA 或 FormatMessageW 取决于是否定义了 BOOST_NO_ANSI_APIS:

  std::string system_error_category::message( int ev ) const
  {
# ifndef BOOST_NO_ANSI_APIS  
    LPVOID lpMsgBuf = 0;
    DWORD retval = ::FormatMessageA( 
        FORMAT_MESSAGE_ALLOCATE_BUFFER | 
        FORMAT_MESSAGE_FROM_SYSTEM | 
        FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,
        ev,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
        (LPSTR) &lpMsgBuf,
        0,
        NULL 
    );
    detail::local_free_on_destruction lfod(lpMsgBuf);
    if (retval == 0)
        return std::string("Unknown error");

    std::string str( static_cast<LPCSTR>(lpMsgBuf) );
# else  // WinCE workaround
    LPVOID lpMsgBuf = 0;
    DWORD retval = ::FormatMessageW( 
        FORMAT_MESSAGE_ALLOCATE_BUFFER | 
        FORMAT_MESSAGE_FROM_SYSTEM | 
        FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,
        ev,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
        (LPWSTR) &lpMsgBuf,
        0,
        NULL 
    );
    detail::local_free_on_destruction lfod(lpMsgBuf);
    if (retval == 0)
        return std::string("Unknown error");

    int num_chars = (wcslen( static_cast<LPCWSTR>(lpMsgBuf) ) + 1) * 2;
    LPSTR narrow_buffer = (LPSTR)_alloca( num_chars );
    if (::WideCharToMultiByte(CP_ACP, 0, static_cast<LPCWSTR>(lpMsgBuf), -1, narrow_buffer, num_chars, NULL, NULL) == 0)
        return std::string("Unknown error");

    std::string str( narrow_buffer );
# endif
    while ( str.size()
      && (str[str.size()-1] == '\n' || str[str.size()-1] == '\r') )
        str.erase( str.size()-1 );
    if ( str.size() && str[str.size()-1] == '.' ) 
      { str.erase( str.size()-1 ); }
    return str;
  }

如果消息调用 FormatMessageW,则字符串变窄为系统默认的 Windows ANSI 代码页 (CP_ACP)

在 Windows 上的所有情况下,结果都是默认的 ANSI 代码页。

关于c++ - boost-asio 错误消息使用的编码是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18489893/

相关文章:

c++ - 尽管与 boost_system 链接,但对 boost::system::generic_category 的 undefined reference

c++ - ShellExecute无法在Windows XP中打开特殊文件夹?

c++ - 我应该使用过滤图或子图还是其他东西?

c++11 - gcc 4.9.2 的 Boost 1.57 文件系统/系统链接器错误

C++ 11 Thread 与 Boost Thread 有什么区别吗?

c++ - 等待异步请求完成

c++ - 使用 boost 的运行时错误 - undefined symbol : _ZN5boost6system15system_categoryEv

c++和注入(inject)的基本名称

c++ - std::string 中的 Malloc 错误

c++ - 在深度 std::unordered_map 中插入唯一指针