To access a structure/class that contains a user-defined structure/class in boot::python

Asked 1 years ago, Updated 1 years ago, 102 views

I want to do this with Boost::python.

C language side

structure A{
    intx;
    inty;
}
US>structure B{
    intid;
    Aa;
}

Python side

b=B()
b.a.x = 0
b.a.y = 1
b.id = 25

I tried Boost.python and found that

boot::python::class_<B>("B")
    .def_readwrite("id", & B::id);

works and the code snippet above corresponds to b.id= 25.
However,

boot::python::class_<B>("B")
    .def_readwrite("a", & B::a);

does not call b.a.x even though it moves up to b.a.

Perhaps there is a special way to write when a member variable of a structure/class includes a user-defined structure/class.
Could you tell me how to write it?

python boost

2022-09-30 15:59

1 Answers

As for the implementation in python 3.7+pybind 11, the following code worked:

src/main.cpp

#include<pybind11/pybind11.h>

US>structure A{
    intx;
    inty;
};

US>structure B{
    intid;
    Aa;
};

namespace py=pybind11;


PYBIND11_MODULE(example,m){

  py::class_<A>(m, "A")
    .def(py::init<int,int>())
    .def_readwrite("x", & A::x)
    .def_readwrite("y", & A::y);

  py::class_<B>(m, "B")
    .def(py::init<int,A>())
    .def_readwrite("id", & B::id)
    .def_readwrite("a", & B::a);
}

sample.py

from example import A,B

a = A (1, 2)    
b = B(1,a)

b.a.x = 0
b.a.y = 1
b.id = 25

print(b.a.x, b.a.y, b.id)

Build with reference to https://github.com/pybind/python_example in pybind11/python_example.

$pip install pybind11
$ pip install.
$ python sample.py
0 1 25


2022-09-30 15:59

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.