I am trying to pass a PyCapsule from C++ to python using pybind11, but cant seem to figure out how to do it. Ive spent a couple of days reading the docs, but cant get my head round how to make this work.
I have created a class that i would like to send to python. I have tried to create an instance of py::capsule in C++ in function getDataTensor and pass that to python using PYBIND11_MODULE. When try the code below, i get the following error msg:
TypeError: Unable to convert function return value to a Python type! The signature was
() -> DLTensor
Any guidance on how to solve this problem would be greatly appreciated.
My code is below:
class DLTensor{
public:
double* data;
int size;
DLTensor():data{new double[10]},size{10}{}
};
py::capsule getDataTensor() {
std::unique_ptr<DLTensor> dlptr =std::unique_ptr<DLTensor>(new DLTensor());
auto pybind_capsule= py::capsule(&dlptr,"DLTensorData",nullptr);
return pybind_capsule;
}
namespace py = pybind11;
PYBIND11_MODULE(DBDLTensor, m) {
m.def("getDataTesor", getDataTensor);
}
I managed to get the code working, so i decided to post my method.
I was missing a py:class_ definition in the PYBIND11_MODULE, and i was missing an ampersand when returning the result to python.
see the working code below:
class DLTensor{
public:
double* data;
int size;
DLTensor():data{new double[10]},size{10}{
}
};
py::capsule getCapsuleDataTensor() {
DLTensor dltensor;
auto pybind_capsule= py::capsule(&dltensor,"dltensor",nullptr);
return pybind_capsule;
}
namespace py = pybind11;
PYBIND11_MODULE(DBDLTensor, m) {
py::class_<DLTensor>(m, "DLTensor");
m.def("getCapsuleDataTensor", &getCapsuleDataTensor);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.