将struct中C结构的数组映射到Cython

2024-06-25 06:04:22 发布

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

更新 GitHub上的最小示例:https://github.com/wl2776/cython_error

我有一个C库,我想从Python访问它。我正在为它开发一个Cython包装。在

库有以下声明:

文件“globals.h”

typedef struct
{
    int x;
    int y;
    int radius;
} circleData;

文件“O\u Recognition.h”

^{pr2}$

我将这些类型映射到.pxd文件中的Cython,如下所示:

文件“cO_识别.pxd“:

cdef extern from "globals.h":
    ctypedef struct circleData:
        int x;
        int y;
        int radius;

cdef extern from "O_Recognition.h":
    ctypedef struct objectData:
        int obj_count;
        circleData circle_data[2];
        float parameters[2];

这不能编译。我收到错误:

Error compiling Cython file:
------------------------------------------------------------
...
    void PyTuple_SET_ITEM(object  p, Py_ssize_t pos, object o)
    void PyList_SET_ITEM(object  p, Py_ssize_t pos, object o)

@cname("__Pyx_carray_to_py_circleData")
cdef inline list __Pyx_carray_to_py_circleData(circleData *v, Py_ssize_t length):
                                                ^
------------------------------------------------------------
carray.to_py:112:45 'circleData' is not a type identifier

还有一个细节,这是CMake项目的一部分,该项目使用GitHub:https://github.com/thewtex/cython-cmake-example

相关部分CMakeLists.txt文件包含具有其他名称的.pyx文件,cimportcDeclarations.pxd文件在


Tags: 文件topyhttpsgithubobjectstructcython
1条回答
网友
1楼 · 发布于 2024-06-25 06:04:22

问题是circleDataO_Recognition.h外部块中未定义。它以前的定义只适用于globals.h外部块。在

只需要包括它的类型,这样Cython就知道它是什么了。不需要重新定义。在

cdef extern from "globals.h" nogil:
    ctypedef struct circleData:
        int x;
        int y;
        int radius;

cdef extern from "O_Recognition.h" nogil:
    ctypedef struct circleData:
        pass
    ctypedef struct objectData:
        int obj_count;
        circleData circle_data[2];
        float parameters[2];

在编译代码时,.c文件将include两个头文件,并从globals.h获取circleData的类型定义。在

从技术上讲,globals.h外部块中的circleData成员的定义也不需要,除非结构成员将在Cython代码中使用。在

记住,pxd文件是Cython代码的定义,而不是C代码。只包含要在Cython代码中使用的成员,否则只能在上面的每个识别外部块中定义sans members per circleData类型。在

相关问题 更多 >