Convert const char* to const wchar_t*

家住魔仙堡 提交于 2019-12-09 06:01:24

问题


I am trying to create a program with Irrlicht that loads certain things from a configuration file written in Lua, one of which is the window title. However, the lua_tostring function returns a const char* while the Irrlicht device's method setWindowCaption expects a const wchar_t*. How can I convert the string returned by lua_tostring?


回答1:


There are multiple questions on SO that address the problem on Windows. Sample posts:

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

There is a platform agnostic method posted at http://ubuntuforums.org/showthread.php?t=1579640. The source from this site is (I hope I am not violating any copyright):

#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 ;
    const ctype<char>& ctfacet = 
                         use_facet< ctype<char> >( 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' ;
  } 
}



回答2:


You can use mbstowcs:

    wchar_t WBuf[100];
    mbstowcs(WBuf,lua_tostring( /*...*/ ),99);

or more safe:

    const char* sz = lua_tostring(/*...*/);
    std::vector<wchar_t> vec;
    size_t len = strlen(sz);
    vec.resize(len+1);
    mbstowcs(&vec[0],sz,len);
    const wchar_t* wsz = &vec[0];



回答3:


For Unicode:

std::string myString = "Master James";
const char* sz = myString.c_str();
size_t origsizes = strlen(sz) + 1;
const size_t newsizes = 500;
size_t convertedCharP = 0;
wchar_t constTowchar[500];
mbstowcs_s(&convertedCharP, constTowchar, origsizes, sz, _TRUNCATE);
std::wcout << constTowchar << std::endl;

This is working using mbstowcs_s.



来源:https://stackoverflow.com/questions/30409350/convert-const-char-to-const-wchar-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!