cython convert void*返回python obj

2024-09-30 01:35:52 发布

您现在位置:Python中文网/ 问答频道 /正文

在要将void*转换回python obj时收到错误消息。在

基于本文 Convert Python object to C void type 转换应该很容易。在

struct _node {
    void * data;
} node;

cpdef match(self, path):
    m = cpyr3.r3_tree_match(self.root, path, NULL)

    if m:
        return <object>m.data

错误消息:

^{pr2}$

我测试了几种方法:

1

Error compiling Cython file:
------------------------------------------------------------
...
        cpyr3.r3_tree_compile(self.root, NULL)

    cpdef match(self, path):
        m = cpyr3.r3_tree_match(self.root, path, NULL)
        if m:
            return <object>(m.data[0])
                            ^
------------------------------------------------------------

cpyr3.pyx:17:29: Cannot convert 'node *' to Python object

2

它将通过编译,但在运行时引发异常

Traceback (most recent call last):
  File "test.py", line 22, in <module>
    print run(r)
  File "test.py", line 13, in run
    return r.match('/foo/bar')
  File "cpyr3.pyx", line 14, in pyr3.R3Tree.match (cpyr3.c:1243)
    cpdef match(self, path):
  File "cpyr3.pyx", line 17, in pyr3.R3Tree.match (cpyr3.c:1186)
    return <object>(m[0].data[0])
AttributeError: 'dict' object has no attribute 'data'

这句话是从哪里来的?在

编辑2:复制问题(包含详细信息):

源回购:https://github.com/lucemia/pyr3/tree/cython

git clone https://github.com/lucemia/pyr3/ -b cython 
cd pyr3
rm cpyr3.c
rm pyr3.c
git submodule init; git submodule update; 
cd r3
./autogen.sh
./configure
cd ..
python setup_cython.py build_ext --inplace

编辑3:

更改cpyr3.pxd 从

cdef extern from "r3.h":
    ctypedef struct node:
        pass

cdef extern from "r3.h":
    ctypedef struct node:
        void *data

解决问题!在


Tags: pathinselfnodetreedatareturnobject
1条回答
网友
1楼 · 发布于 2024-09-30 01:35:52

我测试过了

cdef struct _node:
    void * data
ctypedef _node node

cpdef pack_unpack():
    cdef node my_node = node(<void *>"some object")

    # This is what should be returned
    cdef node *m = &my_node
    return <object>m.data

^{pr2}$

而且效果很好。在

所以我的回答是,可能还有别的事情发生。如果我有一个最小的可运行的样本我可以测试。在

要检查的三个可能错误:

  • m未键入或键入错误

  • self.root或{}是错误的类型

  • _node键入错误。例如,使用cdef struct _node: pass我得到

    Error compiling Cython file:
                                  
    ...
    cpdef pack_unpack():
        cdef node my_node = node(<void *>"some object")
    
        # This is what should be returned
        cdef node *m = &my_node
        return <object>m.data
                       ^
                                  
    
    c_unpacker.pyx:10:20: Cannot convert 'node *' to Python object
    

    发生这种情况是因为根据Cython看到的错误定义,m没有属性{}。在这些场景中,Cython默认转换为Python类型。


通过编译步骤,我设法得出

cdef extern from "r3.h":
    ctypedef struct node:
        pass

这是我清单上的第三点。你应该把它改成

cdef extern from "r3.h":
    ctypedef struct node:
        void *data

这将删除该错误。在

相关问题 更多 >

    热门问题