I need to pass a path from Python to a C++ library using ctypes. If I specify the path as
path = b"..\\xml_mapping_rule\\AixLib_Mapping_Rule.xml"
everything works. But now I have to create the path like this
path = os.path.join(rootPath, "\\AixLib_Mapping_Rule.xml")
which works on Python 2, but not on Python 3. How can I convert the path into a bytearray (I believe this is what the b in front of the string does)?
The closest question I could find here on SO is this one: Passing a path to Labview DLL in Python
Try something like:
path = os.path.join(root_path, "AixLib_Mapping_Rule.xml")
return path.encode('utf-8') # or 'latin-1' or 'cp1252'
In python 2 a string is a sequence of bytes, but in python 3 it is a sequence of unicode codepoints. "Encoding" a string is the process of converting the codepoints to a sequence of bytes.
You must convert the Unicode string to a byte string by encoding it, like one of these:
path = path.encode('ascii')
path = bytes(path, 'ascii')
If you want to use the correct encoding, try sys.getfilesystemencoding()
, like so:
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.