Get the value of a Cython pointer

c, cython, pointers, python

Solution

You can cast a pointer to the appropriate C type, which should then be translated into a Python integer by Cython. The correct C type is `uintptr_t` from `<stddef.h>` which in Cython would be available via `from libc.stdint cimport uintptr_t`. The cast is of course written `<uintptr_t>array_or_pointer`.

Problem

I am writing a function that constructs a malloc'd `unsigned char *` array, and then retuns the pointer. In pure Cython or C, this is easy. All you have to do is set a return type on the function, and return the pointer to the array. Done. However, I have reached a point where I need to return a pointer to an array created in Cython, to Python. I know that a pointer is simply the memory address. Is there any way that I can return a Cython pointer to Python as a python object (such as int or hex, because the memory address is essentially a number), so I can then basically manage pointers in python? I have tried to return the value of the pointer like this: ``` cdef unsigned char array[8] def return_pointer(): return &array ``` This of course does not work because the conversion cant be done. Cython complains with `Cannot convert 'unsigned char (*)[8]' to Python object`. Any suggestions? EDIT: I do not need to access the value in the memory address referenced by the pointer in Python, only pass the pointer around. I then plan to use the Python object pointer, and call c functions with it as an argument.

Original source