blob: ead5b37d79d8f18511844c9c39f7a6c83502ff89 [file] [log] [blame] [view]
Wenzel Jakob10d992e2015-08-04 13:59:51 +02001![pybind11 logo](https://github.com/wjakob/pybind11/raw/master/logo.png)
2
3# pybind11 — Seamless operability between C++11 and Python
Wenzel Jakob38bd7112015-07-05 20:05:44 +02004
5**pybind11** is a lightweight header library that exposes C++ types in Python
6and vice versa, mainly to create Python bindings of existing C++ code. Its
7goals and syntax are similar to the excellent
8[Boost.Python](http://www.boost.org/doc/libs/1_58_0/libs/python/doc/) library
9by David Abrahams: to minimize boilerplate code in traditional extension
10modules by inferring type information using compile-time introspection.
11
12The main issue with Boost.Python—and the reason for creating such a similar
13project—is Boost. Boost is an enormously large and complex suite of utility
14libraries that works with almost every C++ compiler in existence. This
15compatibility has its cost: arcane template tricks and workarounds are
16necessary to support the oldest and buggiest of compiler specimens. Now that
17C++11-compatible compilers are widely available, this heavy machinery has
18become an excessively large and unnecessary dependency.
19
20Think of this library as a tiny self-contained version of Boost.Python with
21everything stripped away that isn't relevant for binding generation. The whole
Wenzel Jakob57082212015-09-04 23:42:12 +020022codebase requires less than 3000 lines of code and only depends on Python (2.7
23or 3.x) and the C++ standard library. This compact implementation was possible
24thanks to some of the new C++11 language features (tuples, lambda functions and
25variadic templates).
Wenzel Jakob38bd7112015-07-05 20:05:44 +020026
27## Core features
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020028The following core C++ features can be mapped to Python
Wenzel Jakob38bd7112015-07-05 20:05:44 +020029
30- Functions accepting and returning custom data structures per value, reference, or pointer
31- Instance methods and static methods
32- Overloaded functions
33- Instance attributes and static attributes
34- Exceptions
35- Enumerations
36- Callbacks
37- Custom operators
38- STL data structures
39- Smart pointers with reference counting like `std::shared_ptr`
40- Internal references with correct reference counting
41
42## Goodies
43In addition to the core functionality, pybind11 provides some extra goodies:
44
45- It's easy to expose the internal storage of custom data types through
46 Pythons' buffer protocols. This is handy e.g. for fast conversion between
47 C++ matrix classes like Eigen and NumPy without expensive copy operations.
48
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020049- pybind11 can automatically vectorize functions so that they are transparently
50 applied to all entries of one or more NumPy array arguments.
51
Wenzel Jakob38bd7112015-07-05 20:05:44 +020052- Python's slice-based access and assignment operations can be supported with
53 just a few lines of code.
54
55- pybind11 uses C++11 move constructors and move assignment operators whenever
56 possible to efficiently transfer custom data types.
57
Wenzel Jakobd4258ba2015-07-26 16:33:49 +020058- It is possible to bind C++11 lambda functions with captured variables. The
59 lambda capture data is stored inside the resulting Python function object.
60
Wenzel Jakob38bd7112015-07-05 20:05:44 +020061## What does the binding code look like?
62Here is a simple example. The directory `example` contains many more.
63```C++
64#include <pybind/pybind.h>
65#include <pybind/operators.h>
66
67namespace py = pybind;
68
69/// Example C++ class which should be bound to Python
70class Test {
71public:
72 Test();
73 Test(int value);
74 std::string toString();
75 Test operator+(const Test &e) const;
76
77 void print_dict(py::dict dict) {
78 /* Easily interact with Python types */
79 for (auto item : dict)
80 std::cout << "key=" << item.first << ", "
81 << "value=" << item.second << std::endl;
82 }
83
84 int value = 0;
85};
86
87
88PYTHON_PLUGIN(example) {
89 py::module m("example", "pybind example plugin");
90
91 py::class_<Test>(m, "Test", "docstring for the Test class")
92 .def(py::init<>(), "docstring for constructor 1")
93 .def(py::init<int>(), "docstring for constructor 2")
94 .def(py::self + py::self, "Addition operator")
95 .def("__str__", &Test::toString, "Convert to a string representation")
96 .def("print_dict", &Test::print_dict, "Print a Python dictionary")
97 .def_readwrite("value", &Test::value, "An instance attribute");
98
99 return m.ptr();
100}
101```
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200102
103## A collection of specific use cases (mostly buffer-related for now)
104For brevity, let's set
105```C++
106namespace py = pybind;
107```
108### Exposing buffer views
109Python supports an extremely general and convenient approach for exchanging
110data between plugin libraries. Types can expose a buffer view which provides
111fast direct access to the raw internal representation. Suppose we want to bind
112the following simplistic Matrix class:
113
114```C++
115class Matrix {
116public:
117 Matrix(size_t rows, size_t cols) : m_rows(rows), m_cols(cols) {
118 m_data = new float[rows*cols];
119 }
120 float *data() { return m_data; }
121 size_t rows() const { return m_rows; }
122 size_t cols() const { return m_cols; }
123private:
124 size_t m_rows, m_cols;
125 float *m_data;
126};
127```
128The following binding code exposes the ``Matrix`` contents as a buffer object,
129making it possible to cast Matrixes into NumPy arrays. It is even possible to
130completely avoid copy operations with Python expressions like
131``np.array(matrix_instance, copy = False)``.
132```C++
133py::class_<Matrix>(m, "Matrix")
134 .def_buffer([](Matrix &m) -> py::buffer_info {
135 return py::buffer_info(
136 m.data(), /* Pointer to buffer */
137 sizeof(float), /* Size of one scalar */
138 py::format_descriptor<float>::value(), /* Python struct-style format descriptor */
139 2, /* Number of dimensions */
140 { m.rows(), m.cols() }, /* Buffer dimensions */
141 { sizeof(float) * m.rows(), /* Strides (in bytes) for each index */
142 sizeof(float) }
143 );
144 });
145```
146The snippet above binds a lambda function, which can create ``py::buffer_info``
147description records on demand describing a given matrix. The contents of
148``py::buffer_info`` mirror the Python buffer protocol specification.
149```C++
150struct buffer_info {
151 void *ptr;
152 size_t itemsize;
153 std::string format;
154 int ndim;
155 std::vector<size_t> shape;
156 std::vector<size_t> strides;
157};
158```
159### Taking Python buffer objects as arguments
160To create a C++ function that can take a Python buffer object as an argument,
161simply use the type ``py::buffer`` as one of its arguments. Buffers can exist
162in a great variety of configurations, hence some safety checks are usually
163necessary in the function body. Below, you can see an basic example on how to
164define a custom constructor for the Eigen double precision matrix
165(``Eigen::MatrixXd``) type, which supports initialization from compatible
166buffer
167objects (e.g. a NumPy matrix).
168```C++
169py::class_<Eigen::MatrixXd>(m, "MatrixXd")
170 .def("__init__", [](Eigen::MatrixXd &m, py::buffer b) {
171 /* Request a buffer descriptor from Python */
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200172 py::buffer_info info = b.request();
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200173
174 /* Some sanity checks ... */
175 if (info.format != py::format_descriptor<double>::value())
176 throw std::runtime_error("Incompatible format: expected a double array!");
177
178 if (info.ndim != 2)
179 throw std::runtime_error("Incompatible buffer dimension!");
180
181 if (info.strides[0] == sizeof(double)) {
182 /* Buffer has the right layout -- directly copy. */
183 new (&m) Eigen::MatrixXd(info.shape[0], info.shape[1]);
184 memcpy(m.data(), info.ptr, sizeof(double) * m.size());
185 } else {
186 /* Oops -- the buffer is transposed */
187 new (&m) Eigen::MatrixXd(info.shape[1], info.shape[0]);
188 memcpy(m.data(), info.ptr, sizeof(double) * m.size());
189 m.transposeInPlace();
190 }
191 });
192```
193
194### Taking NumPy arrays as arguments
195
196By exchanging ``py::buffer`` with ``py::array`` in the above snippet, we can
197restrict the function so that it only accepts NumPy arrays (rather than any
198type of Python object satisfying the buffer object protocol).
199
200In many situations, we want to define a function which only accepts a NumPy
201array of a certain data type. This is possible via the ``py::array_dtype<T>``
202template. For instance, the following function requires the argument to be a
203dense array of doubles in C-style ordering.
204```C++
205void f(py::array_dtype<double> array);
206```
207When it is invoked with a different type (e.g. an integer), the binding code
208will attempt to cast the input into a NumPy array of the requested type.
209
210### Auto-vectorizing a function over NumPy array arguments
211Suppose we want to bind a function with the following signature to Python so
212that it can process arbitrary NumPy array arguments (vectors, matrices, general
213N-D arrays) in addition to its normal arguments:
214```C++
215double my_func(int x, float y, double z);
216```
217This is extremely simple to do!
218```C++
219m.def("vectorized_func", py::vectorize(my_func));
220```
221Invoking the function like below causes 4 calls to be made to ``my_func`` with
222each of the the array elements. The result is returned as a NumPy array of type
Wenzel Jakoba576e6a2015-07-29 17:51:54 +0200223``numpy.dtype.float64``.
Wenzel Jakobd4258ba2015-07-26 16:33:49 +0200224```Python
225>>> x = np.array([[1, 3],[5, 7]])
226>>> y = np.array([[2, 4],[6, 8]])
227>>> z = 3
228>>> result = vectorized_func(x, y, z)
229```
230The scalar argument ``z`` is transparently replicated 4 times. The input
231arrays ``x`` and ``y`` are automatically converted into the right types (they
232are of type ``numpy.dtype.int64`` but need to be ``numpy.dtype.int32`` and
233``numpy.dtype.float32``, respectively)
234
235Sometimes we might want to explitly exclude an argument from the vectorization
236because it makes little sense to wrap it in a NumPy array. For instance,
237suppose the function signature was
238```C++
239double my_func(int x, float y, my_custom_type *z);
240```
241This can be done with a stateful Lambda closure:
242```C++
243// Vectorize a lambda function with a capture object (e.g. to exclude some arguments from the vectorization)
244m.def("vectorized_func",
245 [](py::array_dtype<int> x, py::array_dtype<float> y, my_custom_type *z) {
246 auto stateful_closure = [z](int x, float y) { return my_func(x, y, z); };
247 return py::vectorize(stateful_closure)(x, y);
248 }
249);
250```