2013-04-01 135 views
2

我想從.dll字符串表讀取utf-8測試。 像這樣LPWSTR to wstring C++

LPWSTR nnW; 
LoadStringW(hMod, id, nnW, MAX_PATH); 

之後,我想轉換LPWSTR nnWstd::wstring nnWstring。我試過這種方式: LPWSTR nnW; LoadStringW(hMod,id,nnW,MAX_PATH);

const int length = MultiByteToWideChar(CP_UTF8, 
             0, // no flags required 
             (LPCSTR)nnW, 
             -1, // automatically determine length 
             NULL, 
             0); 

std::wstring nnWstring(length, L'\0'); 

if (!MultiByteToWideChar(CP_UTF8, 
         0, 
         (LPCSTR)nnW, 
         -1, 
         &nnWstring[0], 
         length)) 

MessageBoxW(NULL, (LPCWSTR)nnWstring.c_str(), L"wstring", MB_OK | MB_ICONERROR); 

之後在MessageBoxW中只顯示第一個字母。

+2

你試過了什麼?有一個非常明顯的解決方案。你可能會感興趣的是你知道它和'char *'到'std :: string'是一樣的,因爲它們實際上都是'std :: basic_string '和不同的預定義的'CharT'。 – chris

+0

我更新了我的代碼。 –

+1

你爲什麼叫'MultiByteToWideChar'? 'LoadStringW'和'wstring'都使用寬字符。 –

回答

4

無需轉換或複製。

std::wstring nnWString(MAX_PATH, 0); 
nnWString.resize(LoadStringW(hMod, id, &nnWString[0], nnWString.size()); 

注意:您的原始代碼會導致未定義的行爲,因爲它使用未初始化的指針進行寫入。當然不是你想要的。

這裏的另一種變化:

+0

如果我嘗試你的解決方案我得到這個錯誤: 錯誤:從'int'無效轉換爲'const wchar_t *' 錯誤:'初始化參數1'std :: basic_string <_CharT,_Traits,_Alloc> :: basic_string(const _CharT *,const _Alloc&)[with _CharT = wchar_t,_Traits = std :: char_traits ,_Alloc = std :: allocator ]'' –

+0

@Carl:好的,需要雙參數構造函數來指定初始長度。 –

+0

好的,謝謝它的工作原理,但如果我使用messagebox來顯示結果,我得到這個: http://kepfeltoltes.hu/view/130402/message_www.kepfeltoltes.hu_.png –

1

I would like to read utf-8 test from a .dll string table. something like this

一般情況下,在Windows字符串表是UTF-16。你正試圖把UTF-8數據合併成一個。 UTF-8數據被視爲「擴展的」ASCII,所以每個字節都被擴展爲兩個字節,其中零字節。

您應該直接將UTF-16數據放入字符串表中。

如果您必須將UTF-8數據存儲在資源中,則可以將其放入RCDATA資源並使用較低級別的資源功能來獲取數據。然後,您必須從UTF-8轉換爲UTF-16以將其存儲在wstring中。