How to pass on arrays of raw bytes? #6061
-
|
I'm implementing a python module that allows to create a Msg data type. It takes T: 17, L: 13, V: [2,3,5,7,11,13,17,19,23,127,-128,-127,0], S: [17,0,0,0,13,2,3,5,7,11,13,17,19,23,127,-128,-127,0] V is the actual value and I've got a method that returns that value. However it returns Calling it prints an empty vector: value: [] OK, maybe I did make some mistakes initialising it. So I added a few cout's: The method execution prints: , 1, 1, 1, 1, 11, 13, 17, 19, 23, 127, -128, -127, 1 And the script returns: value: [2, 3, 5, 7, 11, 13, 17, 19, 23, 127, -128, -127, 0] I thought, maybe the code without using the variable gets optimised away (using -O2 as compiler flag). I'm new to C++ and Python, so I'm clearly doing it wrong. What is the correct way |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
|
The root bug is this loop: for(uint i; i < m.getLength(); ++i)
Adding Fix: for (uint i = 0; i < m.getLength(); ++i)That said, if the goal is to return raw bytes to Python, .def("getValue", [](const rav::Msg &m) {
auto data = m.getValue();
return py::bytes(reinterpret_cast<const char *>(data.get()),
static_cast<pybind11::ssize_t>(m.getLength()));
})Python will receive a If you need signed |
Beta Was this translation helpful? Give feedback.
The root bug is this loop:
for(uint i; i < m.getLength(); ++i)iis never initialized. In C++, a local variable likeuint i;has an indeterminate value. If that value happens to be greater than or equal tom.getLength(), the loop body never runs and the returned vector stays emptyAdding
std::cerrchanges the generated code / stack layout enough to mask the bug in that particular build, which is why it may look like an optimization issueFix:
That said, if the goal is to return raw bytes to Python,
py::bytesis usually the simpler option: