Created
December 10, 2024 21:29
-
-
Save afrittoli/82360e7c9005e8130cc998c54f6b0b3a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <pybind11/pybind11.h> | |
#define STRINGIFY(x) #x | |
#define MACRO_STRINGIFY(x) STRINGIFY(x) | |
int add(int i, int j) { | |
return i + j; | |
} | |
struct Breed { | |
Breed(const std::string &name) : name(name) { } | |
void setName(const std::string &name_) { name = name_; } | |
const std::string &getName() const { return name; } | |
std::string name; | |
}; | |
struct Pet { | |
Pet(const Breed &breed) : breed_(breed) { } | |
auto breed() const -> const Breed& { return breed_; } | |
auto breed() -> Breed& { return breed_; } | |
auto str() -> const std::string { return breed_.getName(); } | |
std::string name; | |
Breed breed_; | |
}; | |
namespace py = pybind11; | |
PYBIND11_MODULE(python_example, m) { | |
m.doc() = R"pbdoc( | |
Pybind11 example plugin | |
----------------------- | |
.. currentmodule:: python_example | |
.. autosummary:: | |
:toctree: _generate | |
add | |
subtract | |
)pbdoc"; | |
m.def("add", &add, R"pbdoc( | |
Add two numbers | |
Some other explanation about the add function. | |
)pbdoc"); | |
m.def("subtract", [](int i, int j) { return i - j; }, R"pbdoc( | |
Subtract two numbers | |
Some other explanation about the subtract function. | |
)pbdoc"); | |
py::class_<Breed>(m, "Breed") | |
.def(py::init<const std::string &>()) | |
.def("setName", &Breed::setName) | |
.def("getName", &Breed::getName) | |
.def("__str__", &Breed::getName); | |
py::class_<Pet>(m, "Pet") | |
.def(py::init<const Breed &>()) | |
.def("breed", py::overload_cast<>(&Pet::breed)) | |
.def("constBreed", py::overload_cast<>(&Pet::breed, py::const_)) | |
.def("__str__", &Pet::str); | |
#ifdef VERSION_INFO | |
m.attr("__version__") = MACRO_STRINGIFY(VERSION_INFO); | |
#else | |
m.attr("__version__") = "dev"; | |
#endif | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment