2012-01-12 40 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中编码的字符如“å”?

相关问题