wxString to char* Topic is solved

这是wxWidgets论坛的中文版本。在这里,您可以用您的母语汉语讨论上面任一子论坛所涉及的所有关于wxWidgets的话题。欢迎大家参与到对有价值的帖子的中英互译工作中来!
Post Reply
kingkamg
I live to help wx-kind
I live to help wx-kind
Posts: 187
Joined: Tue Apr 08, 2008 1:45 pm

wxString to char*

Post by kingkamg »

使用Unicode编码方式

Code: Select all

wxString srcPath(wxT("c:\\1.txt"));
char* destPath = (char*)wxConvFileName->cWX2MB( srcPath ).data();
这样转换为何destPath值是乱码,谁知道宽字符怎么转换成窄字符?
liuqi5521
Earned some good credits
Earned some good credits
Posts: 103
Joined: Thu Apr 03, 2008 5:35 am
Location: China
Contact:

Post by liuqi5521 »

试试 .mb_str()
Utensil
Moderator
Moderator
Posts: 423
Joined: Sun Feb 03, 2008 11:38 am
Location: China

Post by Utensil »

话说楼主的方法也忒危险...

在2.8.x中,我们习惯用wxString::c_str(),但到2.9.x,我们就得使用wxString::mb_str()了。这是因为到了2.9.x,没有ANSI与UNICODE BUILD之分,全都变成UNICODE了,而且还是UTF-8这种非定长的编码...所以楼主的data()到时就更会是乱码了。

可参见http://docs.wxwidgets.org/trunk/overvie ... es_unicode,这里有较为详细地介绍。

-Utensil
In fascination of creating worlds by words, and in pursuit of words behind the world.

On Github: http://utensil.github.com
Technical Blog in Chinese: http://utensil.iteye.com/
Utensil
Moderator
Moderator
Posts: 423
Joined: Sun Feb 03, 2008 11:38 am
Location: China

Post by Utensil »

我又看了一遍楼主的代码和wxMBConv的文档,发现:

首先,楼主发帖时可能有个笔误:

char* destPath = (char*)wxConvFileName->cWX2MB( srcPath ).data();

应为

char* destPath = (char*)wxConvFileName->cWX2MB( srcPath.data() );

因为在UNICODE BUILD中,该函数原型为const wxCharBuffer wxMBConv::cWX2MB ( const wxChar * psz ) const,并不接受wxString作为参数,估计楼主是用了data()来转成wxChar*(在这种情况下也就是wchar_t*)。

其次,我猜想,若是把data()换成wc_char(),楼主的代码应该就可以运行了。不过,何苦呢,wxString::mb_str()已经在内部使用了 wxMBConv::cWC2MB做了应做的转换。

有种感觉,wxMBConv是wxWidgets内部用的,我们自己,还是用wxString的wc_str()
utf8_str()
c_str()
wx_str()
mb_str()
fn_str()
吧,应该够强大了。 :wink:

-Utensil
In fascination of creating worlds by words, and in pursuit of words behind the world.

On Github: http://utensil.github.com
Technical Blog in Chinese: http://utensil.iteye.com/
kingkamg
I live to help wx-kind
I live to help wx-kind
Posts: 187
Joined: Tue Apr 08, 2008 1:45 pm

Post by kingkamg »

上面大家提到的mb_str()依然不行,最终使用下面的代码解决,或许是因为wx的版本问题吧,我用的2.8.7一直未做升级

Code: Select all

const wxWX2MBbuf tmp_buf = wxConvCurrent->cWX2MB(OutPath);
char* temp = const_cast<char*>((const char*)tmp_buf);
char* destImgPath = new char[strlen(temp)+1];
strcpy( destImgPath,temp);
zhua278
In need of some credit
In need of some credit
Posts: 1
Joined: Fri Sep 12, 2008 1:51 am

Post by zhua278 »

觉得wxWidgets对字符编码搞的很乱。我是统统变为UTF-8。
Post Reply