Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Py2/3兼容用于ctypes的dll字符串输入_Python_Dll_Unicode_Byte_Compatibility - Fatal编程技术网

Python Py2/3兼容用于ctypes的dll字符串输入

Python Py2/3兼容用于ctypes的dll字符串输入,python,dll,unicode,byte,compatibility,Python,Dll,Unicode,Byte,Compatibility,我正在围绕一个dll创建一个python包装器,并试图使其与Python2和Python3兼容。dll中的某些函数只接受字节并返回字节。这在Py2上很好,因为我可以只处理字符串,但在Py3上,我需要将unicode转换为字节进行输入,然后将字节转换为unicode进行输出 例如: import ctypes from ctypes import util path = util.find_library(lib) dll = ctypes.windll.LoadLibrary(path) d

我正在围绕一个dll创建一个python包装器,并试图使其与Python2和Python3兼容。dll中的某些函数只接受字节并返回字节。这在Py2上很好,因为我可以只处理字符串,但在Py3上,我需要将unicode转换为字节进行输入,然后将字节转换为unicode进行输出

例如:

import ctypes
from ctypes import util

path = util.find_library(lib)
dll = ctypes.windll.LoadLibrary(path)

def some_function(str_input):
   #Will need to convert string to bytes in the case of Py3
   bytes_output = dll.some_function(str_input)
   return bytes_output # Want this to be str (bytes/unicode for py2/3)

确保兼容性的最佳方法是什么?只需使用sys.version\u info并进行适当的编码/解码就可以了,或者在这种情况下,确保版本之间的兼容性的最普遍方式是什么?

我通常会避免对Python解释器版本进行硬检查

您可能会发现此文档很有帮助:

另外,请注意,您可以将此导入用于unicode文本:

from __future__ import unicode_literals
对于字节字符串:

# Python 2 and 3
s = b'This must be a byte-string'
至于将字符串转换为字节的最佳方法:

在Python 3中,将字符串转换为字节的推荐方法(从上面的链接中提取)如下所示:

>>> a = 'some words'
>>> b = a.encode('utf-8')
>>> print(b)
b'some words'
>>> c = b.decode('utf-8')
>>> print(c)
'some words'
>>> isinstance(b, bytes)
True
>>> isinstance(b, str)
False
>>> isinstance(c, str)
True
>>> isinstance(c, bytes)
False

你也可以做
字节(一个'utf-8')
,但是前面提到的方法更像python(因为你可以用同样的方法从
字节
反向解码到
str

好的,太好了!因此,首先使用内置导入字节的
(在Py2上尝试
importorror
)可以只使用
字节(stru输入)
确保字节输入到dll,然后使用say
str(bytes输出)
确保给定Python版本的输出为
str
?以上注释基于第一个链接。在我展示的例子中,没有文字,但我认为在我的代码的其余部分,文字转换将是有用的。这应该是可行的,只要你尝试一下,就像你说的那样。您也可以仅在需要时通过首先断言x是
str
字节的实例来转换。在Python 2中,如果您有
x=b'something'
并选中
isinstance(x,str)
isinstance(x,bytes)
,两者都将返回
True
。然而,在Python3中,
isinstance(x,str)
将返回
False
。这有帮助吗?我编辑了我的答案,以便让您更深入地了解我所说的内容,以及在Python 3中将字节转换为字符串(反之亦然)的最佳方法。@pbreach我不确定您是否使用IDE,但您可能希望查看PyCharm Community Edition的最新版本。它有Python2和Python3类型提示和兼容性检查。