2015-05-23 23 views
5

Sto provando a creare un programma con Irrlicht che carica alcune cose da un file di configurazione scritto in Lua, uno dei quali è il titolo della finestra. Tuttavia, la funzione lua_tostring restituisce un valore const char* mentre il metodo del dispositivo Irrlicht setWindowCaption prevede uno const wchar_t*. Come posso convertire la stringa restituita da lua_tostring?Converti const char * in const wchar_t *

risposta

3

Ci sono più domande su SO che risolvono il problema su Windows. Messaggi di esempio:

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

c'è un metodo agnostica piattaforma pubblicato su http://ubuntuforums.org/showthread.php?t=1579640. La fonte da questo sito è (spero non sto violando i diritti d'autore):

#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' ; 
    } 
} 
+0

dimenticato di chiarire che Sono su ubuntu. Prova la tua risposta ora ... – Giaphage47

+0

In generale, ho scoperto che occuparsi di un testo esteso in C++ in Ubuntu richiede l'impostazione delle impostazioni internazionali predefinite. È molto ironico come si comportano le implementazioni. Con UTF-8 come in Unix-land, le impostazioni locali non sono importanti per la conversione narrow-wide, ma devono essere impostate, mentre con le varie codifiche a byte singolo come in Windows le impostazioni locali sono molto importanti, ma sono già impostate per impostazione predefinita. –

2

È possibile utilizzare mbstowcs:

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

o più sicura:

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]; 
Problemi correlati