I need to build a string in python and pass it to the wrapped C lib. The C lib defines the function:
unsigned char load(char const *FileName)
In the .pyx file:
def test():
PATH = '/usr/lib/libnx.so'
PATH = <char*>PATH
load(PATH)
But I get: TypeError: expected bytes, str found
I have tried encoding the python string but get the same error.
String literals Cython understands all Python string type prefixes: b'bytes' for byte strings. u'text' for Unicode strings. f'formatted {value}' for formatted Unicode string literals as defined by PEP 498 (added in Cython 0.24)
To summarize the previous section: a Unicode string is a sequence of code points, which are numbers from 0 through 0x10FFFF (1,114,111 decimal). This sequence of code points needs to be represented in memory as a set of code units, and code units are then mapped to 8-bit bytes.
Answer: There are 2 types of strings supported by python. Strings stored as characters and stored as bytes. Strings stored as characters are represented as unicode in python 2 or str in python 3.
In Python, str
objects are not byte arrays as in C. To get that, you must encode the string. The default is UTF-8 encoding, which is backwards compatible with ASCII.
Here are two ways to pass the array of bytes:
PATH
to be a bytes
object from the get-go:
PATH = b'/usr/lib/libnx.so'
, or:PATH = 'usr/lib/libnx.so'.encode()
PATH
into a byte array when you pass it:
load(PATH.encode())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With