我需要使用 ctypes 将路径从 Python 传递到 C++ 库。 如果我将路径指定为
path = b"..\\xml_mapping_rule\\AixLib_Mapping_Rule.xml"
一切正常。但现在我必须创建这样的路径
path = os.path.join(rootPath, "\\AixLib_Mapping_Rule.xml")
它适用于 Python 2,但不适用于 Python 3。 如何将路径转换为字节数组(我相信这就是字符串前面的 b 的作用)?
我在这里能找到的最接近的问题是这个: Passing a path to Labview DLL in Python
最佳答案
您必须通过编码将 Unicode 字符串转换为字节字符串,如下所示:
path = path.encode('ascii')
path = bytes(path, 'ascii')
如果您想使用正确的编码,请尝试sys.getfilesystemencoding()
,如下所示:
import ctypes
import os
import sys
libc = ctypes.CDLL('libc.so.6')
fs_enc = sys.getfilesystemencoding()
rootPath = "/tmp"
path = os.path.join(rootPath, "AixLib_Mapping_Rule.xml")
path = path.encode(fs_enc)
fd = libc.open(path, 0, 0)
关于python - 使用 ctypes 将路径从 python 2 和 3 传递到 c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31791026/