QByteArray和python bytes之间的转换

来源:互联网 发布:excel数据图表插件 编辑:程序博客网 时间:2024/04/29 10:22

pyside或者pyqt在pythonV3中,都不存在Qstring类型,取而代之的是python的str类型。但是QByteArray是存在的,在使用pyside的过程中,有可能会使用到QByteArray和python bytes类型之间的转换。google了下,一般都是说QByteArray和bytes之间不用转换,事实上,在使用Qdatastream>>bytes()时,会产生EOFERRO。如下代码:

修改前

  • 先输出

qdatasteam out(file)

out<<obj #obj是python的bytes对象

  • 然后读入

qdatastring in(file)

obj=bytes()

in>>obj    #产生EOFERRO

修改后

经过一个下午的实验终于ok了,代码如下:

  • 先输出

qdatasteam out(file)

out<<qbytearray(obj )#obj是python的bytes对象

#由于C++有隐式转换,也可使是:

out<<obj

  • 然后读入:

qdatastring in(file)

tmp=qbytearray()

in>>tmp

obj=bytes(tmp.data()) #现在读入的obj就是开始保存的二进制对象了

综上:

输出流时C++进行了隐式转换,输入流时C++没有进行隐式转换。不管怎么样,还是手动转换最稳妥。

  • bytes--->qbytearray 是:

obj=bytes()

qbyte=qbytearray(obj)

  • qbytesarray---->bytes是:

qbyte=qbytearray()

obj=qbyte.data()或者obj=bytes(qbyte.data())


我是在串行化时,同时使用pickle和qt造成这个问题。


原创粉丝点击