Skip to content

Inheritance and py::cast #287

Closed
Closed
@aldanor

Description

@aldanor

Maybe I'm missing something obvious, but I couldn't figure why py::cast doesn't respect inheritance properly? Or does it? (I'm trying to get a Python object from a C++ object inside a function in order to do some more stuff with it before returning -- I'd expect py::cast to obey the same rules as return values)

In the example below, I would naturally expect A type to be returned from both functions, whereas for some reason it's B in the second example.

#include <pybind11/pybind11.h>
namespace py = pybind11;

struct A { }; struct B : A { };

PYBIND11_PLUGIN(pb11_inh) {
    py::module m("pb11_inh");
    py::class_<A>(m, "A").def(py::init());
    py::class_<B>(m, "B", py::base<A>()).def(py::init());
    m.def("f1", [](const B& b) { const A& a = b; return a; });
    m.def("f2", [](const B& b) { const A& a = b; return py::cast(a); });
    return m.ptr();
}
>>> from pb11_inh import A, B, f1, f2
>>> b = B()
>>> f1(b)
<pb11_inh.A at 0x7f2b004c4180>  # as expected
>>> f2(b)
<pb11_inh.B at 0x7f2b0191af10>  # ???

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions