英文:
Using Pybind11 and access C++ objects through a base pointer
问题
以下是您要翻译的内容:
假设我有以下的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()
并且正确调用派生类中的函数?
英文:
Suppose I have the following C++ classes:
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>();
}
}
Is it possible, and if so, how, to write a binding using Pybind11 so that I in Python code can write:
dog = animalFactory('dog')
cat = animalFactory('cat')
dog.sound()
cat.sound()
and have the correct functions in the derived classes called?
答案1
得分: 1
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);
}
import examples
dog = examples.animalFactory('Dog')
cat = examples.animalFactory('Cat')
dog.sound()
cat.sound()
英文:
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);
}
I'd recommend reading the docs here: https://pybind11.readthedocs.io/en/stable/advanced/classes.html
Note that with my example, you will need to write the following in python:
import examples
dog = examples.animalFactory('Dog')
cat = examples.animalFactory('Cat')
dog.sound()
cat.sound()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论