[英]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 類型的未捕獲異常終止:無法將“示例”類型的調用參數“變量”轉換為 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 文檔中提供了更多詳細信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.