Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Python object to C void type

Tags:

python

c

cython

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

like image 758
user232343 Avatar asked Jun 03 '13 22:06

user232343


1 Answers

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
like image 133
Gauthier Boaglio Avatar answered Sep 24 '22 13:09

Gauthier Boaglio