【问题标题】:Returning an array of structs in Cython在 Cython 中返回结构数组
【发布时间】:2018-03-12 22:48:16
【问题描述】:

我正在尝试在 Cython 中返回一个结构数组。

// .pyx

from libc.stdint cimport uint8_t

cdef extern from "<apriltag.h>":
    cdef struct apriltag_detection:
        int id
        double c[2]
        double p[4][2]

    ctypedef apriltag_detection apriltag_detection_t

cdef extern from "tag36h11_detector/tag36h11_detector.h":
    apriltag_detection_t* scan_frame(int width, int height, uint8_t* data);

cdef class Detection:
    # how do I "link" this to the struct defined above?
    def __cinit__(self):
        pass
    def __dealloc__(self):
        pass

def detect(width, height, frame):
    return scan_frame(width, height, frame)

理想情况下,我想在 Python 代码中调用 detect 函数,并获取 Detection 对象列表,其中 Detection 是 C 结构 apriltag_detection 的包装类,它的类型定义为 @ 987654328@.

我收到以下编译错误:

tag36h11_detector.pyx:22:21: 无法将 'apriltag_detection_t *' 转换为 Python 对象

我在文档中的任何地方都找不到返回指向结构或结构数组的指针的引用。

更新 3

// .h
typedef struct detection_payload {
    int size;
    apriltag_detection_t** detections;
} detection_payload_t;

我正在尝试将上述结构转换为包含 size 的 Python 对象和包含 apriltag_detection_t 对象的 Python 列表。

// .pyx

cdef extern from "<apriltag.h>":
    cdef struct apriltag_detection:
        int id
        double c[2]
        double p[4][2]

    ctypedef apriltag_detection apriltag_detection_t

cdef extern from "tag36h11_detector/tag36h11_detector.h":
    cdef struct detection_payload:
        int size
        apriltag_detection_t** detections
    ctypedef detection_payload detection_payload_t
    detection_payload* scan_frame(int width, int height, uint8_t* data)

...


cdef class Detection:
    cdef apriltag_detection* _d

    def __cinit__(self):
        self._d = NULL
    cdef _setup(self, apriltag_detection* d):
        self._d = d
    def __dealloc__(self):
        self._d = NULL
    property id:
        def __get__(self):
            return self._d.id
    property c:
        def __get__(self):
            return self._d.c
    property p:
        def __get__(self):
            return self._d.p

cdef Detection_create(apriltag_detection_t* d):
    return Detection()._setup(d)

cdef class DetectionPayload:
    cdef detection_payload* _p

    def __cinit__(self):
        self._p = NULL
    cdef _setup(self, detection_payload* p):
        self._p = p
        self.size = p.size
        self.detections = []
        for i in range(0, self.size):
            apriltag_detection_t* detection = self._p.detections[i]
            d = Detection_create(detection)
            self.detections+=[d]
    def __dealloc__(self):
        _p = NULL
    property size:
        def __get__(self):
            return self.size
    property detections:
        def __get__(self):
            return self.detections

我遇到了几个语法错误:

apriltag_detection_t* detection = self._p.detections[I]

具体来说,在指针apriltag_detection_t*

更新 2

现在可以正常编译和导入。数组仍然没有进展

from libc.stdint cimport uint8_t

cdef extern from "<apriltag.h>":
    cdef struct apriltag_detection:
        int id
        double c[2]
        double p[4][2]

    ctypedef apriltag_detection apriltag_detection_t

cdef extern from "tag36h11_detector/tag36h11_detector.h":
    apriltag_detection_t* scan_frame(int width, int height, uint8_t* data);

cdef class Detection:
    cdef apriltag_detection* _d

    def __cinit__(self):
        self._d = NULL
    cdef _setup(self, apriltag_detection* d):
        self._d = d
    def __dealloc__(self):
        self._d = NULL
    property id:
        def __get__(self):
            return self._d.id
    property c:
        def __get__(self):
            return self._d.c
    property p:
        def __get__(self):
            return self._d.p

cdef Detection_create(apriltag_detection_t* d):
    return Detection()._setup(d)

def detect(width, height, frame):
    cdef apriltag_detection_t* detection = scan_frame(width, height, frame)
    return Detection_create(detection)

更新 1

我尝试按照下面链接的帖子进行操作,这就是我目前所拥有的。

from libc.stdint cimport uint8_t

cdef extern from "<apriltag.h>":
    cdef struct apriltag_detection:
        int id
        double c[2]
        double p[4][2]

    ctypedef apriltag_detection apriltag_detection_t

cdef extern from "tag36h11_detector/tag36h11_detector.h":
    apriltag_detection_t* scan_frame(int width, int height, uint8_t* data);

cdef class Detection:
    cdef apriltag_detection* _d;
    def __cinit__(self):
        self._d = NULL
    def _setup(self, apriltag_detection* d):
        self._d = d
    def __dealloc__(self):
        self._d = NULL
    property id:
        def __get__(self):
            return self._t.id
    property c:
        def __get__(self):
            return self._t.c
    property p:
        def __get__(self):
            return self._t.p

cdef Detection_create(apriltag_detection_t* d):
    return Detection()._setup(d)

def detect(width, height, frame):
    return <Detection>scan_frame(width, height, frame)

虽然这比我以前更接近,但我仍然收到错误:

tag36h11_detector.pyx:33:30: 无法将 'apriltag_detection_t *' 转换为 Python 对象

上线

cdef Detection_create(apriltag_detection_t* d):
    return Detection()._setup(d)

此外,我不知道如何返回 Python 列表...

【问题讨论】:

  • 这非常接近重复的stackoverflow.com/questions/23545875/…。它是关于单个结构而不是数组,但想法非常接近
  • @DavidW 谢谢你,但使用他们的代码会导致同样的错误。我也不知道如何返回 Python 列表...
  • 不是您当前问题的解决方案,而是下一个问题的解决方案;)因为'frame'不是指针cython.readthedocs.io/en/latest/src/tutorial/array.html
  • 顺便说一句,如果scan_frame返回一个数组,你怎么知道数组中有多少个标签?
  • @ead 啊..我不知道!也许我应该返回一个包含大小并指向apriltag_detection_ts 数组的结构?

标签: python c arrays struct cython


【解决方案1】:

您似乎已经解决了您的问题,但我还是想回答这个问题。首先是因为我想尝试一下,其次是因为我认为您在内存管理方面存在一些问题,我想指出这一点。

我们将包装以下简单的 C 接口:

//creator.h
typedef struct {
   int mult;
   int add;
} Result;

typedef struct {
   int size;
   Result *arr;
} ResultArray;

ResultArray create(int size, int *input){
   //whole file at the end of the answer
}

它处理输入数组并返回结构的 C 数组以及该数组中的元素数量。

我们的包装 pyx 文件如下所示:

#result_import.pyx (verion 0)
cdef extern from "creator.h":
     ctypedef struct Result:
          int mult
          int add
     ctypedef struct ResultArray:
          int size
          Result *arr
     ResultArray create(int size, int *input)

def create_structs(int[::1] input_vals):
    pass

最值得注意的部分:我使用 memoryview (int[::1]) 来传递我的输入数组,这有两个优点:

  1. 在 python 端,可以使用任何支持内存视图的东西(numpyarray,因为 Python3),使用 numpy 数组更灵活
  2. 确保(通过[::1])输入是连续的

在测试脚本中我使用 numpy,但也可以使用内置数组:

#test.py
import result_import
import numpy as np

a=np.array([1,2,3],dtype='int32')
result=result_import.create_structs(a)
for i,el in enumerate(result):
    print  i, ": mult:", el.mult, " add:", el.add

现在还没有任何效果,但一切都设置好了。

第一个场景:我们只想拥有普通的 python 对象,没什么特别的!一种可能性是:

#result_import.pyx (verion 1)
#from cpython cimport array needed for array.array in Python2
from libc.stdlib cimport free
....
class PyResult:
    def __init__(self, mult, add):
       self.mult=mult
       self.add=add


def create_structs(int[::1] input_vals):
    cdef ResultArray res=create(len(input_vals), &input_vals[0])
    try:
        lst=[]
        for i in range(res.size):
            lst.append(PyResult(res.arr[i].mult, res.arr[i].add))
    finally:
        free(res.arr)
    return lst  

我将整个数据转换为 python 对象并使用一个简单的列表。很简单,但是有两点值得注意:

  1. 内存管理:我负责释放 res.arr 中分配的内存。所以我使用try...finally 来确保即使抛出异常也会发生。
  2. 将此指针设置为NULL是不够的,我必须调用free-function。

现在我们的 test.py 工作了 - 很好!

第二种情况: 但是,如果我只需要一些元素并将它们全部转换 - 这只是效率低下。此外,我将所有元素两次保存在内存中(至少在一段时间内)——这是幼稚方法的缺点。所以我想在程序稍后的某个地方按需创建PyResult-objects。

让我们写一个包装器列表:

#result_import.pyx (verion 2)
...
cdef class WrappingList:
    cdef int size
    cdef Result *arr

    def __cinit__(self):
        self.size=0
        self.arr=NULL

    def __dealloc__(self):
        free(self.arr)
        print "deallocated"#just a check

    def __getitem__(self, index):
        if index<0 or index>=self.size:
            raise IndexError("list index out of range")
        return PyResult(self.arr[index].mult, self.arr[index].add)


def create_structs(int[::1] input_vals):
    cdef ResultArray res=create(len(input_vals), &input_vals[0])
    lst=WrappingList()
    lst.size, lst.arr=res.size, res.arr
    return lst 

所以WrappingList 类的行为很像一个列表,保留整个 C 数组而不复制,并且仅在需要时创建 PyResult-objects。值得一提的事情:

  1. __dealloc__WrapperingList 对象被销毁时被调用 - 这是我们释放 C 代码给我们的内存的地方。在test.py 的末尾我们应该看到“deallocated”,否则会出错...
  2. __getitem__ 用于迭代。

第三种情况: Python 代码不仅要读取结果,还要更改它们,因此可以将更改后的数据传回 C 代码。为此,让我们将 PyResult 设为代理:

#result_import.pyx (verion 3, last)
...
cdef class PyResult:
    cdef Result *ptr #ptr to my element
    def __init__(self):
       self.ptr=NULL

    @property
    def mult(self):
        return self.ptr.mult

    @mult.setter
    def mult(self, value):
        self.ptr.mult = value

    @property
    def add(self):
        return self.ptr.add

    @add.setter
    def add(self, value):
        self.ptr.add = value


cdef class WrappingList:  
    ...
    def __getitem__(self, index):
        if index>=self.size:
            raise IndexError("list index out of range")
        res=PyResult()
        res.ptr=&self.arr[index]
        return res

现在,PyResult-object 拥有一个指向相应元素的指针,并且可以直接在 C 数组中更改它。但是,有一些陷阱,我应该提一下:

  1. 有点不安全:PyResult 的寿命不应超过父对象-WrappingList-对象。您可以通过在 PyResult-class 中添加对父级的引用来修复它。
  2. 访问元素(addmult)的成本很高,因为每次都必须创建、注册和删除新的 Python 对象。

让我们更改测试脚本,以查看代理的运行情况:

#test.py(second version)
import result_import
import numpy as np

a=np.array([1,2,3],dtype='int32')
result=result_import.create_structs(a)
for i,el in enumerate(result):
    print  i, ": mult:", el.mult, " add:", el.add
    el.mult, el.add=42*i,21*i

# now print changed values:
for i,el in enumerate(result):
    print  i, ": mult:", el.mult, " add:", el.add

还有很多需要改进的地方,但我想一个答案就足够了:)


附件:

马虎creator.h - 需要检查malloc的结果:

//creator.h
typedef struct {
   int mult;
   int add;
} Result;

typedef struct {
   int size;
   Result *arr;
} ResultArray;

ResultArray create(int size, int *input){
   ResultArray res;
   res.size=size;
   res.arr=(Result *)malloc(size*sizeof(Result));//todo: check !=0
   for(int i=0;i<size;i++){
       res.arr[i].mult=2*input[i];
       res.arr[i].add=2+input[i]; 
   }
   return res;
}

setup.py:

from distutils.core import setup, Extension
from Cython.Build import cythonize

setup(ext_modules=cythonize(Extension(
            name='result_import',
            sources = ["result_import.pyx"]
    )))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-20
    • 2014-09-25
    • 2014-06-02
    • 2018-08-10
    • 1970-01-01
    相关资源
    最近更新 更多