2009年5月13日星期三

wxWidgets 中的 C 字符串

wxWidgets 中的 C 字符串
关键字: wxwidgets, lua

在 wxWidgets 中处理 C 语言字符串真是一件令人头痛的事情,因为 wxWidgets 库是 C++ 编写的,类中的成员函数大多使用 wxChar*, wxString 作为参数。然而众所周知,在 C 语言里,字符串是以字符数组的形式存储,所以当 wxWidgets 需要和一些 C 库结合使用的时候,比如 Lua,难免会遇到将 C 字符串实例化成 wxString 或 wxChar* 对象的过程中出现乱码的问题。而且这种乱码的出现与一般编程中遇到的乱码不太一样,使用的转换方法不正确,不论是中文还是英文都会出现乱码,一视同仁。

一开始,我都是按照文档中的例子使用 wxString::Printf 方法进行转换,通常情况下不会有问题,例如:


C++代码

1. wxString temp;
2. temp.Printf(wxT("abc");//字符显示正确
3. temp.Printf(wxT("测试");//字符显示正确

wxString temp;
temp.Printf(wxT("abc");//字符显示正确
temp.Printf(wxT("测试");//字符显示正确




但是使用一段时间之后发现 Printf 函数只能正确得到第一个参数中的字符,其他参数中的字符都会变成乱码,即使是英文字符也会有问题,例如:


C++代码

1. wxString temp;
2. const char * str = "abc";
3. temp.Printf(wxT("%s", "abc");//temp会包含乱码
4. temp.Printf(wxT("%s", str);//temp会包含乱码

wxString temp;
const char * str = "abc";
temp.Printf(wxT("%s", "abc");//temp会包含乱码
temp.Printf(wxT("%s", str);//temp会包含乱码




阅读官方文档后,我发现 wxWidgets 还提供了另外一个函数 wxString::FromUTF8,函数声明如下:


C++代码

1. static wxString FromUTF8(const char* s)
2. static wxString FromUTF8(const char* s, size_t len)

static wxString FromUTF8(const char* s)
static wxString FromUTF8(const char* s, size_t len)




使用 wxString::FromUTF8 就可以顺利地解决问题,而且这还是一个静态函数,不需要实例化就可以调用,函数执行成功会返回 wxString 的一个实例:


C++代码

1. const char * str = "abc";
2. wxString::FromUTF8("abc");//返回 wxString 实例,值为"abc"
3. wxString::FromUTF8(str);//返回值与上一条语句相同

const char * str = "abc";
wxString::FromUTF8("abc");//返回 wxString 实例,值为"abc"
wxString::FromUTF8(str);//返回值与上一条语句相同




如果遇到要将 wxString 转化成为 char* 的情况,有三个函数可供使用:wxString::c_str(), wxString::wc_str(), wxString::mb_str()

mb_str returns a C string representation of the string, a const char*, regardless of whether Unicode is enabled. In Unicode mode, the string is converted, and data may be lost.

wc_str returns a wide character representation of the string, a wchar_t*, regardless of whether Unicode is enabled. In ANSI mode, the string is converted to Unicode.

c_str returns a pointer to the string data (const char* in ANSI mode, const wchar_t* in Unicode mode). No conversion takes place.

没有评论: