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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值