Car*_*izz 5 c python arrays struct cython
我试图在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)
Run Code Online (Sandbox Code Playgroud)
理想情况下,我想detect在Python代码中调用该函数,并获取一个Detection对象列表,其中Detection是一个类型为apriltag_detectiondede 的C结构的包装类apriltag_detection_t.
我收到以下编译错误:
tag36h11_detector.pyx:22:21:无法将'apriltag_detection_t*'转换为Python对象
我找不到在文档中的任何地方返回指向结构或结构数组的指针的引用.
更新3
// .h
typedef struct detection_payload {
int size;
apriltag_detection_t** detections;
} detection_payload_t;
Run Code Online (Sandbox Code Playgroud)
我正在尝试将上面的结构转换为包含的Python对象size和保存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
Run Code Online (Sandbox Code Playgroud)
我在线上遇到了几个语法错误:
apriltag_detection_t* detection = self._p.detections[I]
Run Code Online (Sandbox Code Playgroud)
具体来说,在指针上 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)
Run Code Online (Sandbox Code Playgroud)
更新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)
Run Code Online (Sandbox Code Playgroud)
虽然这比我以前更接近,但我仍然得到错误:
tag36h11_detector.pyx:33:30:无法将'apriltag_detection_t*'转换为Python对象
在线上
cdef Detection_create(apriltag_detection_t* d):
return Detection()._setup(d)
Run Code Online (Sandbox Code Playgroud)
而且,我不知道如何返回Python列表......
看来你的问题已经解决了,但我还是想回答一下这个问题。首先是因为我想尝试一下,其次是因为我认为您在内存管理方面存在一些问题,我想指出这一点。
我们将包装以下简单的 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
}
Run Code Online (Sandbox Code Playgroud)
它处理输入数组并返回一个结构体的 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
Run Code Online (Sandbox Code Playgroud)
最值得注意的部分:我使用内存视图(int[::1])来传递我的输入数组,这有两个优点:
numpy从arrayPython3 开始),这比使用 numpy 数组更灵活[::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
Run Code Online (Sandbox Code Playgroud)
现在还没有任何进展,但一切都已准备就绪。
第一种情况:我们只想拥有普通的 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
Run Code Online (Sandbox Code Playgroud)
我将整个数据转换为 python 对象并使用一个简单的列表。很简单,但是有两点值得注意:
try...finally确保它发生。NULL,我必须调用free-function 。现在我们的test.py作品——很好!
第二种情况:但是,如果我只需要一些元素并将它们全部转换 - 它的效率很低。此外,我将所有元素保留在内存中两次(至少一段时间) - 这是幼稚方法的缺点。所以我想PyResult在程序稍后的某个地方按需创建对象。
让我们写一个包装列表:
#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
Run Code Online (Sandbox Code Playgroud)
因此,该类的WrappingList行为很像一个列表,保留整个 C 数组而不进行复制,并且PyResult仅在需要时创建对象。值得一提的事情:
__dealloc__当对象被销毁时调用WrapperingList- 这是我们释放 C 代码提供给我们的内存的地方。最后test.py我们应该看到“解除分配”,否则就会出问题......__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
Run Code Online (Sandbox Code Playgroud)
现在,PyResult-object 持有一个指向相应元素的指针,并且可以直接在 C 数组中更改它。然而,有一些陷阱,我应该提到:
PyResult不应该比父WrappingList对象的寿命长。您可以通过在类中添加对父级的引用来修复它PyResult。add或mult) 的成本相当高,因为每次都必须创建、注册然后删除一个新的 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
Run Code Online (Sandbox Code Playgroud)
还有很多需要改进的地方,但我想一个答案就足够了:)
附件:
草率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;
}
Run Code Online (Sandbox Code Playgroud)
设置.py:
from distutils.core import setup, Extension
from Cython.Build import cythonize
setup(ext_modules=cythonize(Extension(
name='result_import',
sources = ["result_import.pyx"]
)))
Run Code Online (Sandbox Code Playgroud)