Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cython Pass String To C as Bytes

Tags:

python

c

cython

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.

like image 361
BAR Avatar asked Feb 08 '17 06:02

BAR


People also ask

How do you declare a string in Cython?

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)

What is Unicode string in Python?

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.

What are two internal subtypes of string data in Python?

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.


1 Answers

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:

  • Option 1: Define PATH to be a bytes object from the get-go:
    • PATH = b'/usr/lib/libnx.so', or:
    • PATH = 'usr/lib/libnx.so'.encode()
  • Option 2: Encode PATH into a byte array when you pass it:
    • load(PATH.encode())
like image 104
Greg Schmit Avatar answered Oct 04 '22 09:10

Greg Schmit