basics.rst 10.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
.. _basics:

First steps
###########

This sections demonstrates the basic features of pybind11. Before getting
started, make sure that development environment is set up to compile the
included set of examples, which also double as test cases.


Compiling the test cases
========================

Linux/MacOS
-----------

On Linux  you'll need to install the **python-dev** or **python3-dev** packages as
well as **cmake**. On Mac OS, the included python version works out of the box,
but **cmake** must still be installed.

After installing the prerequisites, run

.. code-block:: bash

   cmake .
   make -j 4

followed by

.. code-block:: bash

   make test

Windows
-------

On Windows, use the `CMake GUI`_ to create a Visual Studio project. Note that
only the 2015 release and newer versions are supported since pybind11 relies on
various C++11 language features that break older versions of Visual Studio.
40
After running CMake, open the created :file:`pybind11.sln` file and perform a
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
release build, which will will produce a file named
:file:`Release\\example.pyd`. Copy this file to the :file:`example` directory
and run :file:`example\\run_test.py` using the targeted Python version.

.. _`CMake GUI`: https://cmake.org/runningcmake

.. Note::

    When all tests fail, make sure that

    1. The Python binary and the testcases are compiled for the same processor
       type and bitness (i.e. either **i386** or **x86_64**)

    2. The Python binary used to run :file:`example\\run_test.py` matches the
       Python version specified in the CMake GUI. This is controlled via
       the ``PYTHON_EXECUTABLE`` ``PYTHON_INCLUDE_DIR``, and
       ``PYTHON_LIBRARY`` variables.

.. seealso::

    Advanced users who are already familiar with Boost.Python may want to skip
    the tutorial and look at the test cases in the :file:`example` directory,
    which exercise all features of pybind11.

Creating bindings for a simple function
=======================================

Let's start by creating Python bindings for an extremely simple function, which
adds two numbers and returns their result:

.. code-block:: cpp

    int add(int i, int j) {
        return i + j;
    }

For simplicity [#f1]_, we'll put both this function and the binding code into
a file named :file:`example.cpp` with the following contents:

.. code-block:: cpp

82
    #include <pybind11/pybind11.h>
Wenzel Jakob's avatar
Wenzel Jakob committed
83

84
85
86
87
    int add(int i, int j) {
        return i + j;
    }

88
    namespace py = pybind11;
89

90
    PYBIND11_PLUGIN(example) {
91
        py::module m("example", "pybind11 example plugin");
92
93
94
95
96
97

        m.def("add", &add, "A function which adds two numbers");

        return m.ptr();
    }

98
The :func:`PYBIND11_PLUGIN` macro creates a function that will be called when an
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
``import`` statement is issued from within Python. The next line creates a
module named ``example`` (with the supplied docstring). The method
:func:`module::def` generates binding code that exposes the
``add()`` function to Python. The last line returns the internal Python object
associated with ``m`` to the Python interpreter.

.. note::

    Notice how little code was needed to expose our function to Python: all
    details regarding the function's parameters and return value were
    automatically inferred using template metaprogramming. This overall
    approach and the used syntax are borrowed from Boost.Python, though the
    underlying implementation is very different.

pybind11 is a header-only-library, hence it is not necessary to link against
any special libraries (other than Python itself). On Windows, use the CMake
build file discussed in section :ref:`cmake`. On Linux and Mac OS, the above
example can be compiled using the following command

.. code-block:: bash

John Travers's avatar
John Travers committed
120
    $ c++ -O3 -shared -std=c++11 -I <path-to-pybind11>/include `python-config --cflags --ldflags --libs` example.cpp -o example.so
121
122
123
124
125
126
127
128
129
130
131
132

In general, it is advisable to include several additional build parameters
that can considerably reduce the size of the created binary. Refer to section
:ref:`cmake` for a detailed example of a suitable cross-platform CMake-based
build system.

Assuming that the created file :file:`example.so` (:file:`example.pyd` on Windows)
is located in the current directory, the following interactive Python session
shows how to load and execute the example.

.. code-block:: python

Wenzel Jakob's avatar
Wenzel Jakob committed
133
    $ python
134
135
136
137
138
139
    Python 2.7.10 (default, Aug 22 2015, 20:33:39)
    [GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.1)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import example
    >>> example.add(1, 2)
    3L
Wenzel Jakob's avatar
Wenzel Jakob committed
140
    >>>
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175

.. _keyword_args:

Keyword arguments
=================

With a simple modification code, it is possible to inform Python about the
names of the arguments ("i" and "j" in this case).

.. code-block:: cpp

    m.def("add", &add, "A function which adds two numbers",
          py::arg("i"), py::arg("j"));

:class:`arg` is one of several special tag classes which can be used to pass
metadata into :func:`module::def`. With this modified binding code, we can now
call the function using keyword arguments, which is a more readable alternative
particularly for functions taking many parameters:

.. code-block:: python

    >>> import example
    >>> example.add(i=1, j=2)
    3L

The keyword names also appear in the function signatures within the documentation.

.. code-block:: python

    >>> help(example)

    ....

    FUNCTIONS
        add(...)
176
            Signature : (i: int, j: int) -> int
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211

            A function which adds two numbers

.. _default_args:

Default arguments
=================

Suppose now that the function to be bound has default arguments, e.g.:

.. code-block:: cpp

    int add(int i = 1, int j = 2) {
        return i + j;
    }

Unfortunately, pybind11 cannot automatically extract these parameters, since they
are not part of the function's type information. However, they are simple to specify
using an extension of :class:`arg`:

.. code-block:: cpp

    m.def("add", &add, "A function which adds two numbers",
          py::arg("i") = 1, py::arg("j") = 2);

The default values also appear within the documentation.

.. code-block:: python

    >>> help(example)

    ....

    FUNCTIONS
        add(...)
212
            Signature : (i: int = 1, j: int = 2) -> int
213
214
215
216
217
218
219
220
221
222

            A function which adds two numbers

.. _supported_types:

Supported data types
====================

The following basic data types are supported out of the box (some may require
an additional extension header to be included). To pass other data structures
Wenzel Jakob's avatar
Wenzel Jakob committed
223
as arguments and return values, refer to the section on binding :ref:`classes`.
224

225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
+----------------------------+--------------------------+-----------------------+
|  Data type                 |  Description             | Header file           |
+============================+==========================+=======================+
| int8_t, uint8_t            | 8-bit integers           | pybind11/pybind11.h   |
+----------------------------+--------------------------+-----------------------+
| int16_t, uint16_t          | 16-bit integers          | pybind11/pybind11.h   |
+----------------------------+--------------------------+-----------------------+
| int32_t, uint32_t          | 32-bit integers          | pybind11/pybind11.h   |
+----------------------------+--------------------------+-----------------------+
| int64_t, uint64_t          | 64-bit integers          | pybind11/pybind11.h   |
+----------------------------+--------------------------+-----------------------+
| ssize_t, size_t            | Platform-dependent size  | pybind11/pybind11.h   |
+----------------------------+--------------------------+-----------------------+
| float, double              | Floating point types     | pybind11/pybind11.h   |
+----------------------------+--------------------------+-----------------------+
| bool                       | Two-state Boolean type   | pybind11/pybind11.h   |
+----------------------------+--------------------------+-----------------------+
| char                       | Character literal        | pybind11/pybind11.h   |
+----------------------------+--------------------------+-----------------------+
244
245
| wchar_t                    | Wide character literal   | pybind11/pybind11.h   |
+----------------------------+--------------------------+-----------------------+
246
247
248
249
| const char *               | UTF-8 string literal     | pybind11/pybind11.h   |
+----------------------------+--------------------------+-----------------------+
| std::string                | STL dynamic UTF-8 string | pybind11/pybind11.h   |
+----------------------------+--------------------------+-----------------------+
250
251
| std::wstring               | STL dynamic wide string  | pybind11/pybind11.h   |
+----------------------------+--------------------------+-----------------------+
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
| std::pair<T1, T2>          | Pair of two custom types | pybind11/pybind11.h   |
+----------------------------+--------------------------+-----------------------+
| std::tuple<....>           | Arbitrary tuple of types | pybind11/pybind11.h   |
+----------------------------+--------------------------+-----------------------+
| std::complex<T>            | Complex numbers          | pybind11/complex.h    |
+----------------------------+--------------------------+-----------------------+
| std::array<T, Size>        | STL static array         | pybind11/stl.h        |
+----------------------------+--------------------------+-----------------------+
| std::vector<T>             | STL dynamic array        | pybind11/stl.h        |
+----------------------------+--------------------------+-----------------------+
| std::map<T1, T2>           | STL ordered map          | pybind11/stl.h        |
+----------------------------+--------------------------+-----------------------+
| std::unordered_map<T1, T2> | STL unordered map        | pybind11/stl.h        |
+----------------------------+--------------------------+-----------------------+
| std::set<T>                | STL ordered set          | pybind11/stl.h        |
+----------------------------+--------------------------+-----------------------+
| std::unordered_set<T>      | STL unordered set        | pybind11/stl.h        |
+----------------------------+--------------------------+-----------------------+
| std::function<...>         | STL polymorphic function | pybind11/functional.h |
+----------------------------+--------------------------+-----------------------+
272
273
274
275
276


.. [#f1] In practice, implementation and binding code will generally be located
         in separate files.