pybind11 icon indicating copy to clipboard operation
pybind11 copied to clipboard

[BUG]: How to return a array of structure from cpp to python

Open Winneee opened this issue 4 years ago • 1 comments

Required prerequisites

  • [X] Make sure you've read the documentation. Your issue may be addressed there.
  • [X] Search the issue tracker and Discussions to verify that this hasn't already been reported. +1 or comment there if it has.
  • [X] Consider asking first in the Gitter chat room or in a Discussion.

Problem description

Hi, I have a struct:

typedef struct values
{
	float x;
	float y;
	float w;
	float h;	
}val;
typedef struct Name
{
	unsigned int  num;
	val *data;
}name;

and i am creating a instance of name: name data = Null; and storing desired values in data like ex: data. num = 10

and in wrapper

PYBIND11_MODULE(pybind11_example, m) {
    m.doc() = "pybind11 example plugin"; // Optional module docstring

    py::class_<val>(m, "values")
        .def(py::init<>())
        .def_readwrite("x", &val::x)
        .def_readwrite("y", &val::y)
        .def_readwrite("w", &val::w)
        .def_readwrite("h", &val::h);

    py::class_<name>(m, "name")
        .def(py::init<>())
        .def_readwrite("num", &name::num)
        .def_readwrite("num", &name::data);

}

N di am returning data from cpp code. But whenever i try to call (pybind11_example.num)i am able to get only 0th address data Please suggest correct way to bind.

Reproducible example code

No response

Winneee avatar Dec 10 '21 12:12 Winneee


#include <pybind11/pybind11.h>
#include <pybind11/stl.h>

namespace py = pybind11;

typedef struct {
    float x;
    float y;
    float w;
    float h;
} val;

typedef struct {
    unsigned int num;
    std::shared_ptr<val> data;
} name;

PYBIND11_MODULE(pybind11_example, m) {
    m.doc() = "pybind11 example plugin"; // Optional module docstring

    py::class_<val>(m, "val")
        .def(py::init<>())
        .def_readwrite("x", &val::x)
        .def_readwrite("y", &val::y)
        .def_readwrite("w", &val::w)
        .def_readwrite("h", &val::h);

    py::class_<name>(m, "name")
        .def(py::init<>())
        .def_readwrite("num", &name::num)
        .def_readwrite("data", &name::data);
}

ljluestc avatar Nov 23 '24 21:11 ljluestc