2 years ago

#72065

test-img

wojciech-graj

Cython cast changes underlying data?

Casting in C only changes how the data is interpreted, however the data stored in memory remains the same. By this logic, a char* cast before a void* cast should be equivalent to just having a void* cast. Using memcpy in the Cython snippet, casting to void* without a prior char* cast causes a different value to be copied.

from libc.string cimport memcpy

cdef char cchar = b'\x00'
bstring = b'\x0F'

memcpy(<void*>&cchar, <void*>bstring, 1)
print(cchar)

memcpy(<void*>&cchar, <void*><char*>bstring, 1)
print(cchar)

Output:

3
15

Why does this happen?

Edit: As jérôme-richard noted, the cast to char* changes the bytestring to its c-string representation, while the direct cast to void* provides the entire PyObject's raw memory.

Is there a list of casts which can be applied to specific python types that change their underlying data, as is the case with the char* cast on a bytestring?

python

casting

cython

0 Answers

Your Answer

Accepted video resources