How can I convert Python object to C void type using Cython?
Currently I am getting this message when I try to cast
Casting temporary Python object to non-numeric non-Python type
This can be done like this :
1. Cast from Python to C
If you really meant void *
this would be :
some_pyobj = "abc"
cdef void *ptr
ptr = <void *>some_pyobj
If you meant PyObject *
this would be :
cdef PyObject *ptr
ptr = <PyObject *>some_pyobj # Cast from Python object to C pointer
Then, from C side, the PyObject struct
is available by including Python.h
.
Here is the reference (from object.h
Python include file) :
/* Nothing is actually declared to be a PyObject, but every pointer to
* a Python object can be cast to a PyObject*. This is inheritance built
* by hand. Similarly every pointer to a variable-size Python object can,
* in addition, be cast to PyVarObject*.
*/
typedef struct _object {
PyObject_HEAD
} PyObject;
2. Cast from C to Python
It works in both ways, meaning that the following is also possible :
cdef PyObject *ptr
ptr = <PyObject *>some_pyobj
cdef object some_other_pyobj
some_other_pyobj = <object>ptr # Cast from C pointer to Python object
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