PYBIND11_MODULE(example, m) { //m.def("add", &add, "A function which adds two numbers"); // 变为关键字参数 m.def("add", &add, "A function which adds two numbers", py::arg("i"), py::arg("j")); } // python调用:example.add(i=1, j=2)
设置默认值类似(NOTE: C++接口中定义的默认值不会自动捕获,需要bind时设置):
1 2 3 4
PYBIND11_MODULE(example, m) { // 设置参数默认值 m.def("add", &add, "A function which adds two numbers", py::arg("i") = 1, py::arg("j") = 2); }
classPyAnimal :public Animal { public: /* Inherit the constructors */ using Animal::Animal;
/* Trampoline (need one for each virtual function) */ std::stringgo(int n_times)override{ /* 对纯虚函数使用此宏 */ /* 对有默认实现的虚函数,使用PYBIND11_OVERLOAD*/ PYBIND11_OVERLOAD_PURE( std::string, /* Return type */ Animal, /* Parent class */ go, /* Name of function in C++ (must match Python name) */ n_times /* Argument(s) */ ); } };
classExample { private: Example(int); // private constructor public: // Factory function - returned by value: static Example create(int a){ return Example(a); }
// These constructors are publicly callable: Example(double); Example(int, int); Example(std::string); };
py::class_<Example>(m, "Example") // Bind the factory function as a constructor: .def(py::init(&Example::create)) // Bind a lambda function returning a pointer wrapped in a holder: .def(py::init([](std::string arg) { returnstd::unique_ptr<Example>(new Example(arg)); })) // Return a raw pointer: .def(py::init([](int a, int b) { returnnew Example(a, b); })) // You can mix the above with regular C++ constructor bindings as well: .def(py::init<double>()) ;
#include<pybind11/factory.h> classExample { public: // ... virtual ~Example() = default; }; classPyExample :public Example { public: using Example::Example; // 第一种方式:跳转类以右值引用方式接收基类 PyExample(Example &&base) : Example(std::move(base)) {} }; py::class_<Example, PyExample>(m, "Example") // Returns an Example pointer. If a PyExample is needed, the Example instance will be moved via the extra constructor in PyExample, above. .def(py::init([]() { returnnew Example(); })) // 第二种方式:提供两个工厂函数 .def(py::init([]() { returnnew Example(); } /* no alias needed */, []() { returnnew PyExample(); } /* alias needed */)) // *Always* returns an alias instance (like py::init_alias<>()) .def(py::init([]() { returnnew PyExample(); })) ;