使用 pybind11 将自定义结构(指针向量)从 C++ 传递到 python 的方法是什么?

What is the way to pass a custom made struct (vector of pointers) from C++ to python using pybind11?

本文关键字:python 是什么 方法 C++ 自定义 pybind11 结构 向量 指针 使用      更新时间:2023-10-16

对于一个项目,我需要将一个C++结构作为输入传递给python。 我对C++不是很熟悉,所以我很难理解如何做到这一点。 我得到的错误是:

libc++abi.dylib:以 pybind11::cast_error 类型的未捕获异常终止:无法将类型为"Example"的调用参数"变量"转换为 Python 对象

因为我显然没有告诉 python 如何准确地转换结构。

我将非常感谢有关如何执行此操作的任何提示或反馈。 谢谢:)

//example.cpp
#include <pybind11/pybind11.h>
#include <pybind11/embed.h>
#include <pybind11/stl.h>
#include <memory>

// USE TO COMPILE: g++ -fPIC `python3 -m pybind11 --includes` -undefined dynamic_lookup -std=c++11 -O2 example.cpp -o example -L/usr/local/Cellar/python/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/ `python3-config --libs`
using namespace std;
namespace py = pybind11;
using namespace py::literals; // to bring in the `_a` literal
int MAX_LEN=10;
typedef double Real;
struct Example
{
Example()
{
vector1.reserve(MAX_LEN);
vector2.reserve(MAX_LEN);
}
std::vector<std::vector<Real>> vector1;
std::vector<std::vector<Real>> vector2;
~Example() { clear(); }
void clear()
{
vector1.clear();
vector2.clear();
}
};
PYBIND11_EMBEDDED_MODULE(exampleModule, m){
py::class_<Example>(m, "Example")
.def(py::init<>());
}

int main(void){
py::scoped_interpreter guard{};
py::dict locals;
Example ex;
ex.vector1 = std::vector <vector<Real>> (MAX_LEN, vector<Real>(MAX_LEN, 1.0));
ex.vector2 = std::vector <vector<Real>> (MAX_LEN, vector<Real>(MAX_LEN, 2.0));
locals = py::dict("variable"_a=ex);
py::exec(R"(
print(variable)
)", py::globals(), locals);

return 0;
}

您需要为Example结构添加绑定。 这与为类添加绑定的工作方式相同,例如:

py::class_(m, "example") .def(py::init()) .def_readwrite("vector1", &example::vector1)

对于 STL 向量类型,请记住也包括pybind11/stl.h

pybind11 文档中提供了更多详细信息。