使用 pybind11 将自定义结构(指针向量)从 C++ 传递到 python 的方法是什么?
What is the way to pass a custom made struct (vector of pointers) from C++ to python using pybind11?
对于一个项目,我需要将一个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 文档中提供了更多详细信息。
相关文章:
- python集合的C++等价物是什么.计数器
- 在 c++ 或 python 中生成一个体面的视差图以在 Raspberry Pi 上实现的最佳方法(算法或函数)是什么
- 是什么导致我的 Python 紧缩 C 扩展崩溃?
- 在C++和Python之间交换数据的最快方法是什么?
- Python的"in"运算符的C++等价物是什么?
- Python的追加方法C++等价物是什么?
- 在这段 python 代码中,大于符号是什么意思
- C++和Python之间平等含义的区别的根源是什么?
- 在 Python 中使用 C/C++ 的最快方法是什么?
- python的导入C++等价物是什么?
- 使用 pybind11 将自定义结构(指针向量)从 C++ 传递到 python 的方法是什么?
- 在QTcpSocket和python套接字之间交换数据的正确方法是什么?
- 这个boost.python程序中的错误是什么?
- 用SWIG包装对象从C++调用Python函数的最干净方法是什么
- 在python中,while(cin >> var)的等价物是什么?
- 将C++代码与Python接口的最佳方式是什么
- python中等价的C/C++loselose算法是什么
- Boost.Python中的dispatch函数和forwarding函数是什么意思
- “致命的 Python 错误:PyThreadState_Get:没有当前线程”是什么意思
- 与Ada记录/C++结构类型对应的Python是什么