Replies: 2 comments
-
Hi @chenci107 , I hope this solves your problem. I need to guess without reproducer itself 😅 If you want pybind to correctly translate types you need to register them first. In your case you need to define #include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <sstream>
namespace py = pybind11;
PYBIND11_MODULE(mymodule, m)
{
m.doc() = "This is the module test";
// First register "base classes"
py::class_<MotorData> motor(m, "MotorData");
motor.def(py::init([](float pos, float vel, float tor, float temperature) {
MotorData _motordata{pos, vel, tor, temperature};
return _motordata;
}));
motor.def("__repr__", [](const MotorData& self){
std::ostringstream _stream;
_stream << "(" << self.pos << ", " << self.vel << ", " << self.tor << ", " << self.temperature << ")";
return _stream.str();
});
// "Higher" class can be defined now
py::class_<RobotData> robot(m, "RobotData");
robot.def(py::init([](std::vector<MotorData>& vec) {
RobotData _robotdata{};
std::copy(vec.begin(), vec.end(), _robotdata.joint_data);
return _robotdata;
}));
// Helper function to return C-style array
robot.def_property_readonly("joint_data", [](RobotData& self){
std::vector<MotorData> _tmp;
for(size_t i = 0; i < 12; i++) {
_tmp.push_back(self.joint_data[i]);
}
return _tmp;
});
} It will work in Python like this: In [1]: from mymodule import MotorData, RobotData
...: motors = [MotorData(i, i + 0.1, i + 0.2, i + 0.4) for i in range(0, 12)]
...: robot = RobotData(motors)
...: print(robot.joint_data)
[(0, 0.1, 0.2, 0.4), (1, 1.1, 1.2, 1.4), (2, 2.1, 2.2, 2.4), (3, 3.1, 3.2, 3.4), (4, 4.1, 4.2, 4.4), (5, 5.1, 5.2, 5.4), (6, 6.1, 6.2, 6.4), (7, 7.1, 7.2, 7.4), (8, 8.1, 8.2, 8.4), (9, 9.1, 9.2, 9.4), (10, 10.1, 10.2, 10.4), (11, 11.1, 11.2, 11.4)] You do not need to create initialisers and printing functions, they are here for demo purposes. You should bind each property to your liking. I hope everything is clear now, I am waiting for your feedback. Cheers! |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I have defined the structure MotorData and RobotData, and used MotorData in RobotData, as shown below:
I follow the method in the official tutorial, as shown below
However, since MotorData is defined outside RobotData, an error will be reported, that is, MotorData is not a member of RobotData.
How can I solve this problem without changing my structure?
Beta Was this translation helpful? Give feedback.
All reactions