Pybind11: How to represent union as part of pybind11 class?

Created on 18 Feb 2019  路  2Comments  路  Source: pybind/pybind11

I'm trying to use pybind11 for embedding python.

within that I have a C struct including a union inside. Question is what is the proper way to define it? I.e.:

.def ("UnionName", &C_Struct::UnionName)...
Searched the web and didn't find the answer, nor at pybind documentation or test examples

Most helpful comment

Guess you can bind it using properties(?):

typedef union _UnionName
{
    Type1 Field1;
    Type2 Field2;
} UnionName;
    py::class_<UnionName>(m, "UnionName")
        .def(py::init<>())
        .def_property("Field1",
            [](UnionName& self) -> const Type1& 
            {
                return self.Field1;
            },
            [](UnionName& self, const Type1& value)
            {
                self.Field1 = value;
            });
        .def_property("Field2",
            [](UnionName& self) -> const Type2& 
            {
                return self.Field2;
            },
            [](UnionName& self, const Type2& value)
            {
                self.Field2 = value;
            });

I did not test that but it might help...

All 2 comments

Guess you can bind it using properties(?):

typedef union _UnionName
{
    Type1 Field1;
    Type2 Field2;
} UnionName;
    py::class_<UnionName>(m, "UnionName")
        .def(py::init<>())
        .def_property("Field1",
            [](UnionName& self) -> const Type1& 
            {
                return self.Field1;
            },
            [](UnionName& self, const Type1& value)
            {
                self.Field1 = value;
            });
        .def_property("Field2",
            [](UnionName& self) -> const Type2& 
            {
                return self.Field2;
            },
            [](UnionName& self, const Type2& value)
            {
                self.Field2 = value;
            });

I did not test that but it might help...

Thanks for the suggestion, I am currently on other issues, but I'll try it when I get back to it

Was this page helpful?
0 / 5 - 0 ratings