c++ - 将 const char* 转换为 const wchar_t*

标签 c++ type-conversion irrlicht

我正在尝试使用 Irrlicht 创建一个程序,该程序从用 Lua 编写的配置文件中加载某些内容,其中之一是窗口标题。但是,lua_tostring 函数返回一个 const char*,而 Irrlicht 设备的方法 setWindowCaption 需要一个 const wchar_t*。如何转换 lua_tostring 返回的字符串?

最佳答案

SO 上有多个问题可以解决 Windows 上的问题。示例帖子:

  1. char* to const wchar_t * conversion
  2. conversion from unsigned char* to const wchar_t*

http://ubuntuforums.org/showthread.php?t=1579640 上发布了一个与平台无关的方法.该网站的来源是(我希望我没有侵犯任何版权):

#include <locale>
#include <iostream>
#include <string>
#include <sstream>
using namespace std ;

wstring widen( const string& str )
{
    wostringstream wstm ;
    const ctype<wchar_t>& ctfacet = use_facet<ctype<wchar_t>>(wstm.getloc()) ;
    for( size_t i=0 ; i<str.size() ; ++i ) 
              wstm << ctfacet.widen( str[i] ) ;
    return wstm.str() ;
}

string narrow( const wstring& str )
{
    ostringstream stm ;

    // Incorrect code from the link
    // const ctype<char>& ctfacet = use_facet<ctype<char>>(stm.getloc());

    // Correct code.
    const ctype<wchar_t>& ctfacet = use_facet<ctype<wchar_t>>(stm.getloc());

    for( size_t i=0 ; i<str.size() ; ++i ) 
                  stm << ctfacet.narrow( str[i], 0 ) ;
    return stm.str() ;
}

int main()
{
  {
    const char* cstr = "abcdefghijkl" ;
    const wchar_t* wcstr = widen(cstr).c_str() ;
    wcout << wcstr << L'\n' ;
  }
  {  
    const wchar_t* wcstr = L"mnopqrstuvwx" ;
    const char* cstr = narrow(wcstr).c_str() ;
    cout << cstr << '\n' ;
  } 
}

关于c++ - 将 const char* 转换为 const wchar_t*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30409350/

相关文章:

c++ - 在 C++ 中向管道发送命令

c++ - std::tuple 的笛卡尔积

c++ - 3D 和 UI 工具包

c++ - Irrlicht:如何将 ISceneNode 转换为 IMeshSceneNode?

c++ - 从文件读取 diskpart 错误

c++ - C++ 标准是否明确允许/禁止使用不完整类型实例化 std::function?

c++ - C++ 标准是否指定在某些情况下编译应该失败并出现错误?

javascript - 如何在 Javascript 中将一个变量转换为另一个变量的类型

ios - Objective C在哪里存储对象,堆或堆栈

c++ - Irrlicht Gui 鼠标不会点击按钮