1. Header and namespace conventions
假定: 本文及后续pybind11教程中均已经包含如下代码。
#include <pybind11/pybind11.h>
namespace py = pybind11;
pybind11有些特性需要包含其他的头文件,这个视具体情况而定。
2. Creating bindings for a simple function
#include <pybind11/pybind11.h>
int add(int i, int j) {
return i + j;
}
PYBIND11_MODULE(example, m) {
m.doc() = "pybind11 example plugin"; // optional module docstring
m.def("add", &add, "A function which adds two numbers");
}
通常源代码和包裹的代码是放在不同的文件中,这里为了便于展示,放在了同一个文件中。
参数解释说明:
PYBIND11_MODULE()
macro :creates a function that will be called when an import statement is issued from within Python.module name (example)
: the first macro argument (it should not be in quotes).The second argument (m)
: defines a variable of typepy::module
, which is the main interface for creating bindings.- The method
module::def()
: generates binding code that exposes the add() function to Python.
构建如上代码会产生动态链接库,如下展示了python如何加载和执行example
:
$ python
Python 2.7.10 (