2012-01-12 38 views
1

我在變量中有一個字符串,而且該字符串來自項目的核心部分。現在我想將其轉換爲unicode字符串。我怎麼能這樣做 並添加L或_T()或TEXT()不是一個選項。 爲了進一步弄清事情請查看下面將字符串轉換爲C中的Unicode

Void foo(char* string) { 
    //Here the contents of the variable STRING should be converted to Unicode 
    //The soln should be possible to use in C code. 
} 

TIA 納文

+4

什麼平臺?或者你想要一個可移植的unicode庫嗎? 「unicode」是什麼意思?你的意思是UTF-16?這個字符串是什麼格式?如果它是純粹的ASCII,那就沒有什麼可做的了,ASCII是unicode的一個子集,所以如果它是ASCII的話,它就是unicode。 – 2012-01-12 08:42:45

+0

感謝您的閃電答覆,這裏我的實際需要是,我使用SafeArrayPutElement,併爲此api的第三個參數是一個void *,在我的情況下,我想傳遞字符串,所以如果我直接通過char *字符串的API沒有說出內存。但爲了測試目的,如果我使用(L「ChkIt」)工作正常。所以如何'L'(轉換爲unicode)字符串變量的內容TIA – Naveen 2012-01-12 09:00:27

+0

所以你想要將窄字符轉換爲寬字符? – tripleee 2012-01-12 09:16:39

回答

1

L用於創建wchar_t的文字。

從您的評論對SafeArrayPutElement你我們術語「統一」的方式很明顯你使用Windows。假設該char* string在編碼的Windows所遺留的使用,而不是UTF-8或東西(在Windows上一個安全的假設),你可以通過以下方式一個wchar_t的字符串:如果您在使用C

// typical Win32 conversion in C 
int output_size = MultiByteToWideChar(CP_ACP,0,string,-1,NULL,0); 
wchar *wstring = malloc(output_size * sizeof(wchar_t)); 
int size = MultiByteToWideChar(CP_ACP,0,string,-1,wstring,output_size); 
assert(output_size==size); 

// make use of wstring here 

free(wstring); 

++你可能想使該異常使用的std :: wstring的,而不是安全的(這裏使用了C++ 11一點點,所以可能需要VS2010或以上):

std::wstring ws(output_size,L'\0'); 
int size = MultiByteToWideChar(CP_ACP,0,string,-1,ws.data(),ws.size()); 
// MultiByteToWideChar tacks on a null character to mark the end of the string, but this isn't needed when using std::wstring. 
ws.resize(ws.size() -1); 

// make use of ws here. You can pass a wchar_t pointer to a function by using ws.c_str() 

//std::wstring handles freeing the memory so no need to clean up 

下面是一個使用更多的另一種方法C++標準庫(並且利用VS2010不完全符合標準):

#include <locale> // for wstring_convert and codecvt 

std::wstring ws = std::wstring_convert<std::codecvt<wchar_t,char,std::mbstate_t>,wchar_t>().from_bytes(string); 

// use ws.c_str() as before 

也意味着你的努力轉化爲wchar_t的意見,並得到了同樣的錯誤。如果這種情況下,當你嘗試這些方法轉換爲wchar_t然後錯誤在別處。可能在字符串的實際內容中。也許它不是正確的空終止?

+0

Bames你好,感謝您的回答,完美的作品......再次感謝很多 – Naveen 2012-01-13 08:49:13

0

你不能說 「轉換爲Unicode」。您需要指定編碼,Unicode不是一種編碼,而是(大致)一個字符集和一組編碼,以將這些字符表示爲字節序列。

同時,還必須指定輸入編碼,怎麼會是如在string中編碼的字符如「å」?

相關問題