python 使用Pybind11并通过基指针访问C++对象

8yoxcaq7  于 2023-05-27  发布在  Python
关注(0)|答案(1)|浏览(275)

假设我有以下C++类:

class Animal {
    public:
    virtual void sound() = 0;
};

class Dog : public Animal {
    public:
    void sound() override {
        std::cout << "Woof\n";
    }
};

class Cat : public Animal {
    public:
    void sound() override {
        std::cout << "Miao\n";
    }
};

std::unique_ptr<Animal> animalFactory(std::string_view type) {
    if (type == "Dog") {
        return std::make_unique<Dog>();
    } else {
        return std::make_unique<Cat>();
    }
}

是否有可能,如果有,如何使用Pybind11编写绑定,以便我在Python代码中可以编写:

dog = animalFactory('dog')
cat = animalFactory('cat')
dog.sound()
cat.sound()

并在派生类中调用正确的函数?

rggaifut

rggaifut1#

PYBIND11_MODULE(examples, m) {

    py::class_<Animal>(m, "Animal");

    py::class_<Dog, Animal>(m, "Dog")
        .def(py::init())
        .def("sound", &Dog::sound);

    py::class_<Cat, Animal>(m, "Cat")
        .def(py::init())
        .def("sound", &Cat::sound);

    m.def("animalFactory", &animalFactory);
}

我建议阅读这里的文档:https://pybind11.readthedocs.io/en/stable/advanced/classes.html
注意,在我的例子中,你需要用python写以下代码:

import examples
dog = examples.animalFactory('Dog')
cat = examples.animalFactory('Cat')
dog.sound()
cat.sound()

相关问题