5

如何使用 Cython 将 Python 对象转换为 C void 类型?

目前,当我尝试投射时收到此消息

将临时 Python 对象转换为非数字非 Python 类型

4

2 回答 2

10

这可以这样做:

1. 从 Python 转换为 C

如果你真的是void *这个意思:

some_pyobj = "abc"
cdef void *ptr
ptr = <void *>some_pyobj

如果您的意思PyObject *是:

cdef PyObject *ptr
ptr = <PyObject *>some_pyobj           # Cast from Python object to C pointer

然后,从 C 端,PyObject struct可以通过包含Python.h.

这是参考(来自object.hPython 包含文件):

/* 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. 从 C 转换为 Python

它以两种方式工作,这意味着以下也是可能的:

cdef PyObject *ptr
ptr = <PyObject *>some_pyobj
cdef object some_other_pyobj
some_other_pyobj = <object>ptr          # Cast from C pointer to Python object
于 2013-06-06T00:31:49.593 回答
1

你可以:

def run():
   pyobj = 'abc'
   pyobj_void_star = <void *>pyobj
于 2013-06-04T01:39:13.143 回答