Skip to content

Subclass python class in C++ #1193

Closed
Closed
@Xfel

Description

@Xfel

I'm trying to create a C++ class that inherits from a python class. However, it does not work. Here is a short example of what i'm trying to do:

foo.py:

class Foo():
    def test():
         raise NotImplementedError

bar.cpp

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

class FooImpl {
public:
    void test() {
        std::cout << "Hello world!" << std::endl;
    }
};

PYBIND11_MODULE(bar, m) {
    py::object foo = (py::object) py::module::import("foo").attr("Foo");
    py::class_<FooImpl>(m, "FooImpl", foo)
        .def(py::init())
        .def("test", &FooImpl::test);
}

When importing the bar module, I get multiple errors. First of all, I get a failed assertion in https://github.com/pybind/pybind11/blob/master/include/pybind11/detail/class.h#L604. This can be solved by adding the py::dynamic_attr() tag to the class definition. However, then I get a segmentation fault in https://github.com/pybind/pybind11/blob/master/include/pybind11/pybind11.h#L916.

So I wonder if this could be supported directly. Of course I could just write my c++ class, and then make a thin wrapper in python inheriting from the python class, but that is just a lot more tedious.

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