使用 ctypes 将 python 2 和 3 的路径传递给 c++
pass a path from python 2 and 3 to c++ using ctypes
我需要使用 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 所做的)?
我能在 SO 上找到的最接近的问题是这个:
试试这样的:
path = os.path.join(root_path, "AixLib_Mapping_Rule.xml")
return path.encode('utf-8') # or 'latin-1' or 'cp1252'
在 python 2 中,字符串是一个字节序列,但在 python 3 中,它是一个 unicode 代码点序列。 "Encoding" 字符串是将代码点转换为字节序列的过程。
您必须通过编码将 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)
我需要使用 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 所做的)?
我能在 SO 上找到的最接近的问题是这个:
试试这样的:
path = os.path.join(root_path, "AixLib_Mapping_Rule.xml")
return path.encode('utf-8') # or 'latin-1' or 'cp1252'
在 python 2 中,字符串是一个字节序列,但在 python 3 中,它是一个 unicode 代码点序列。 "Encoding" 字符串是将代码点转换为字节序列的过程。
您必须通过编码将 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)