Convert Python object to C void type

前端 未结 2 1816
梦如初夏
梦如初夏 2020-12-17 03:25

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-nu

相关标签:
2条回答
  • 2020-12-17 04:18

    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
    
    0 讨论(0)
  • 2020-12-17 04:22

    You can:

    def run():
       pyobj = 'abc'
       pyobj_void_star = <void *>pyobj
    
    0 讨论(0)
提交回复
热议问题