wxWidgets 中的 C 字符串 mb_str


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

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

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



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

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



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

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



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

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.

原文链接: https://www.cnblogs.com/RichardLee/archive/2013/01/24/2875350.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    wxWidgets 中的 C 字符串 mb_str

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/76672

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 下午5:36
下一篇 2023年2月9日 下午5:36

相关推荐