使用pybind11将数组指针从c++传递到python

2024-10-03 02:32:33 发布

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

我想从python中的c++库中获取一个数组的指针,并将其保存在一个变量中,然后将该变量用作另一个c++函数的参数。你知道吗

环境

ubuntu18.04、pybind11、python3.6.8

试过

C类型

passing-pointer-to-c-from-python-using-pybind11

代码

C++ +<

// class1:
static complex<double>* randomComplexArray(long size);

complex<double>* randomComplexArray(long n){
    complex<double>* res = new complex<double>[n];
    for ...
    return res; //pointer
}

// class2:
void calc(complex<double>* vals);

pybuind11型

// class1:
.def_static("randomComplexArray", &class1::randomCircleArray)

// class2:
.def("calc", (void (*)(complex<double>*)) &class2::calc)

Python

p = randomComplexArray(1024)
calc(p) // what I hope

Segmentation faultBus fault等等。你知道吗

我是第一次做这件事。如果有人能帮我?你知道吗

非常感谢!你知道吗


Tags: defstaticcalcres数组longpybind11double