/* #include <pybind11/pybind11.h> namespace py = pybind11; int add(int i, int j) { return i + j; } struct Pet { Pet(const std::string &name) : name(name) { } void setName(const std::string &name_) { name = name_; } const std::string &getName() const { return name; } std::string name; }; /* module: examplelib target: examplelib cpp: example.cpp */ PYBIND11_MODULE(examplelib, m) { // optional module docstring m.doc() = "pybind11 example plugin";
// FUNCTIONS // expose add function, and add keyword arguments and default arguments m.def("add", &add, "A function which adds two numbers", py::arg("i") = 1, py::arg("j") = 2);
// DATA // exporting variables m.attr("the_answer") = 42; py::object world = py::cast("World"); m.attr("what") = world;
python3 Python 3.5.3 (v3.5.3:1880cb95a742, Jan 162017, 16:02:32) [MSC v.190064 bit (AMD64)] on win32 Type"help", "copyright", "credits"or"license"for more information. >>> import examplelib >>> help(examplelib) Help on module examplelib:
NAME examplelib - pybind11 example plugin
CLASSES pybind11_builtins.pybind11_object(builtins.object) Pet
classPet(pybind11_builtins.pybind11_object) | Method resolution order: | Pet | pybind11_builtins.pybind11_object | builtins.object | | Methods defined here: | | __init__(...) | __init__(self: examplelib.Pet, arg0: str) -> None | | getName(...) | getName(self: examplelib.Pet) -> str | | setName(...) | setName(self: examplelib.Pet, arg0: str) -> None | | ---------------------------------------------------------------------- | Methods inherited from pybind11_builtins.pybind11_object: | | __new__(*args, **kwargs) from pybind11_builtins.pybind11_type | Create andreturn a new object. See help(type) for accurate signature.
FUNCTIONS add(...) method of builtins.PyCapsule instance add(i: int = 1, j: int = 2) -> int
/* import sys print sys.path print "Hello,World!" */ py::module sys = py::module::import("sys"); py::print(sys.attr("path")); py::print("Hello, World!"); // use the Python API
/* import example n = example.add(1,2) */ py::module example = py::module::import("example"); py::object result = example.attr("add")(1, 2); int n = result.cast<int>(); assert(n == 3); std::cout << "result from example.add(1,2) = " << n << std::endl;
/* from example import MyMath obj = MyMath("v0") obj.my_add(1,2) */ py::object MyMath = py::module::import("example").attr("MyMath"); // class py::object obj = MyMath("v0"); // class object py::object my_add = obj.attr("my_add");// object method py::object result2 = my_add(1, 2); // result int n2 = result2.cast<int>(); // cast from python type to c++ type assert(n2 == 3); std::cout << "result from obj.my_add(1,2) = " << n2 << std::endl;
/* from example import MyMath obj = MyMath("v0") obj.my_strcon("abc","123"); */