C++模型
假设我有以下要向Python公开的C++数据结构.
#include <memory>
#include <vector>
struct mystruct
{
int a, b, c, d, e, f, g, h, i, j, k, l, m;
};
typedef std::vector<std::shared_ptr<mystruct>> mystruct_list;
Run Code Online (Sandbox Code Playgroud)
提升Python
我可以使用boost :: python使用以下代码相当有效地包装它们,轻松地允许我使用现有的mystruct(复制shared_ptr)而不是重新创建现有对象.
#include "mystruct.h"
#include <boost/python.hpp>
using namespace boost::python;
BOOST_PYTHON_MODULE(example)
{
class_<mystruct, std::shared_ptr<mystruct>>("MyStruct", init<>())
.def_readwrite("a", &mystruct::a);
// add the rest of the member variables
class_<mystruct_list>("MyStructList", init<>())
.def("at", &mystruct_list::at, return_value_policy<copy_const_reference>());
// add the rest of the member functions
}
Run Code Online (Sandbox Code Playgroud)
用Cython
在Cython中,我不知道如何从mystruct_list中提取项目,而不复制底层数据.我不知道如何MyStruct从现有的初始化shared_ptr<mystruct>,而不是以各种形式复制所有数据.
from libcpp.memory cimport shared_ptr
from cython.operator cimport …Run Code Online (Sandbox Code Playgroud) 我刚刚开始熟悉Cython,试图将一些C语言结构包装到Python方法和类中.我真正不了解的是如何从(初始化的)C结构转换到相应的Python类应该可行.我在这里想念的是什么:
C头文件的片段:
struct test_struct {
int _something;
complex_struct* _another;
};
typedef struct test_struct test;
test *test_new(void);
int some_method(test **n, int irrelevant);
Run Code Online (Sandbox Code Playgroud)
来自我的.pxd的相应片段:
cdef struct test_struct:
pass
ctypedef test_struct test
test* test_new()
int some_method(test **n, int irrelevant)
Run Code Online (Sandbox Code Playgroud)
我的.pyx:
def do_something(int irrelevant):
cdef test* t = test_new()
ret = some_method(&t, irrelevant)
# Here comes the problem...
return <Test?>t
cdef class Test:
cdef test* _t
# cinit here and some methods here. No members except _t
Run Code Online (Sandbox Code Playgroud)
返回声明的所有内容都可以正常工作.我得到一个正确的值ret,等等.但返回语句中的强制转换似乎不正确或缺少更多信息.发出t = do_something(42)Python段错误时. …
我试图在 Cython 中调用 C 函数,标题如下所示:
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
#include <ctype.h>
#include <unistd.h>
#include <math.h>
#include <apriltag.h>
#include <tag36h11.h>
#include <common/getopt.h>
#include <common/image_u8.h>
#include <common/image_u8x4.h>
#include <common/pjpeg.h>
#include <common/zarray.h>
apriltag_detection_t* scan_frame(int width, int height, uint8_t* data);
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,我想返回一个结构数组,其类型定义为apriltag_detection_t. 根据文档,为了能够在 Cython 中使用它,我必须定义某种pxd文件,它本质上是标头的副本。
然而,apriltag_detection_t是一个已经在 中定义的类型apriltag.h。此外,apriltag_detection_t具有已在 中定义的成员apriltag.h。在能够使用此库之前,我是否必须在 Cython 文件中递归地重新定义所有这些类型(手动)?我该把它们写在哪里?
谢谢!
更新6
终于到了包装函数的步骤了!
from libc.stdint cimport uint8_t
cdef extern from "<apriltag.h>":
cdef struct apriltag_detection:
int id
double c[2]
double …Run Code Online (Sandbox Code Playgroud)