Py2/3 与 ctypes 一起使用的 dll 的字符串输入的兼容性
Py2/3 compatibility for string input to dll used with ctypes
我正在围绕一个 dll 创建一个 python 包装器,并试图使其与 Python 2 和 3 兼容。dll 中的一些函数只接受字节和 return 字节。这在 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_info
和 encode/decode 会好吗?或者在这种情况下确保版本之间兼容性的最可接受的方法是什么?
我通常会避免硬检查 Python 解释器版本。
您可能会发现此文档有帮助:
http://python-future.org/compatible_idioms.html#strings-and-bytes
此外,请注意您可以将此导入用于 unicode 文字:
from __future__ import unicode_literals
对于字节串:
# Python 2 and 3
s = b'This must be a byte-string'
关于将字符串转换为字节的最佳方法:
在 Python 3 中将字符串转换为字节的推荐方法(从上面的 link 中提取)如下:
>>> 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
你也可以做 bytes(a, 'utf-8')
,但是前面提到的方法更 Pythonic(因为你可以反向 decode
从 bytes
回到 str
).
我正在围绕一个 dll 创建一个 python 包装器,并试图使其与 Python 2 和 3 兼容。dll 中的一些函数只接受字节和 return 字节。这在 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_info
和 encode/decode 会好吗?或者在这种情况下确保版本之间兼容性的最可接受的方法是什么?
我通常会避免硬检查 Python 解释器版本。
您可能会发现此文档有帮助: http://python-future.org/compatible_idioms.html#strings-and-bytes
此外,请注意您可以将此导入用于 unicode 文字:
from __future__ import unicode_literals
对于字节串:
# Python 2 and 3
s = b'This must be a byte-string'
关于将字符串转换为字节的最佳方法:
在 Python 3 中将字符串转换为字节的推荐方法(从上面的 link 中提取)如下:
>>> 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
你也可以做 bytes(a, 'utf-8')
,但是前面提到的方法更 Pythonic(因为你可以反向 decode
从 bytes
回到 str
).