QString 转 wchar_t*

  这两天浪费了一点时间在编码转换上。我们使用到的一个算法库,接口参数是一个wchar_t*,作为文件路径。经过实验,几种方法都没有用,是个麻烦问题。记录一下。找到了下面三种可以工作的方式。

方法1:

file = filename.toStdWString();

const wchar_t* str1 = file.c_str();

 

Returns a std::wstring object with the data contained in this QString. The std::wstring is encoded in utf16 on platforms where wchar_t is 2 bytes wide (e.g. windows) and in ucs4 on platforms where wchar_t is 4 bytes wide (most Unix systems).

  这是最朴素的想法。也是最好使用的办法。很奇怪的是,我前几次测试,却是debug看到了乱码,我也不确定是否是改动了其他宏或者build参数导致的。不过,后来的测试表明,这种方式才是正确的方式,可能存在的问题最小。

 

方法2:

wchar_t str2[256] = {0};

auto  xxx = filename.toWCharArray(str2);

  这种方法是查询QString 文档而知的。但是,这种方式要谨慎,若不对数组str2 初始化,debug可以看到字符串最后会多出来一两个字符,完全随机的。还要注意数组长度。

 

方法3:

const wchar_t * encodedName = reinterpret_cast<const wchar_t  *>(filename.utf16());

  虽然这种方法也能工作,但是需要注意。这里用到了强转,reinterpret_cast 表达式不会编译成任何 CPU 指令,它纯粹是一个编译时指令,指示编译器将 表达式 视为如同具有 新类型 类型一样处理。亦即,与C写法,(const wchar_t  *)ptr 并没有什么不同。

 

  其实,最重要的,我们还是需要知道 OS 使用的编码方式。

C:\Users\kt>chcp

活动代码页: 936

这就是 GB2312 了。每个汉字及符号以两个字节来表示。

Fills the array with the data contained in this QString object. The array is encoded in utf16 on platforms where wchar_t is 2 bytes wide (e.g. windows) and in ucs4 on platforms where wchar_t is 4 bytes wide (most Unix systems).

所以,方法3,只能在windows上使用,在Linux上,还需要注意。

 

至于从wchar_t* 转换为QString的方式,直接参看QString的接口,上述1、3方法对应的接口有fromStdWString、fromUtf16,应该可以解决问题。

 

 

  1. https://zh.wikipedia.org/zh-hans/GB_2312

  2. https://doc.qt.io/qt-5/qstring.html#toStdWString

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值