blob: 1f40f198dbdfbc42d93b07d828ac547a93491588 [file] [log] [blame]
Wenzel Jakob28f98aa2015-10-13 02:57:16 +02001.. _basics:
2
3First steps
4###########
5
6This sections demonstrates the basic features of pybind11. Before getting
7started, make sure that development environment is set up to compile the
8included set of examples, which also double as test cases.
9
10
11Compiling the test cases
12========================
13
14Linux/MacOS
15-----------
16
17On Linux you'll need to install the **python-dev** or **python3-dev** packages as
18well as **cmake**. On Mac OS, the included python version works out of the box,
19but **cmake** must still be installed.
20
21After installing the prerequisites, run
22
23.. code-block:: bash
24
25 cmake .
26 make -j 4
27
28followed by
29
30.. code-block:: bash
31
32 make test
33
34Windows
35-------
36
37On Windows, use the `CMake GUI`_ to create a Visual Studio project. Note that
38only the 2015 release and newer versions are supported since pybind11 relies on
39various C++11 language features that break older versions of Visual Studio.
Wenzel Jakob8f4eb002015-10-15 18:13:33 +020040After running CMake, open the created :file:`pybind11.sln` file and perform a
Wenzel Jakob28f98aa2015-10-13 02:57:16 +020041release build, which will will produce a file named
42:file:`Release\\example.pyd`. Copy this file to the :file:`example` directory
43and run :file:`example\\run_test.py` using the targeted Python version.
44
45.. _`CMake GUI`: https://cmake.org/runningcmake
46
47.. Note::
48
49 When all tests fail, make sure that
50
51 1. The Python binary and the testcases are compiled for the same processor
52 type and bitness (i.e. either **i386** or **x86_64**)
53
54 2. The Python binary used to run :file:`example\\run_test.py` matches the
55 Python version specified in the CMake GUI. This is controlled via
56 the ``PYTHON_EXECUTABLE`` ``PYTHON_INCLUDE_DIR``, and
57 ``PYTHON_LIBRARY`` variables.
58
59.. seealso::
60
61 Advanced users who are already familiar with Boost.Python may want to skip
62 the tutorial and look at the test cases in the :file:`example` directory,
63 which exercise all features of pybind11.
64
65Creating bindings for a simple function
66=======================================
67
68Let's start by creating Python bindings for an extremely simple function, which
69adds two numbers and returns their result:
70
71.. code-block:: cpp
72
73 int add(int i, int j) {
74 return i + j;
75 }
76
77For simplicity [#f1]_, we'll put both this function and the binding code into
78a file named :file:`example.cpp` with the following contents:
79
80.. code-block:: cpp
81
Wenzel Jakob8f4eb002015-10-15 18:13:33 +020082 #include <pybind11/pybind11.h>
Wenzel Jakob93296692015-10-13 23:21:54 +020083
Wenzel Jakob28f98aa2015-10-13 02:57:16 +020084 int add(int i, int j) {
85 return i + j;
86 }
87
Wenzel Jakob10e62e12015-10-15 22:46:07 +020088 namespace py = pybind11;
Wenzel Jakob28f98aa2015-10-13 02:57:16 +020089
Wenzel Jakobb1b71402015-10-18 16:48:30 +020090 PYBIND11_PLUGIN(example) {
Wenzel Jakob8f4eb002015-10-15 18:13:33 +020091 py::module m("example", "pybind11 example plugin");
Wenzel Jakob28f98aa2015-10-13 02:57:16 +020092
93 m.def("add", &add, "A function which adds two numbers");
94
95 return m.ptr();
96 }
97
Wenzel Jakobb1b71402015-10-18 16:48:30 +020098The :func:`PYBIND11_PLUGIN` macro creates a function that will be called when an
Wenzel Jakob28f98aa2015-10-13 02:57:16 +020099``import`` statement is issued from within Python. The next line creates a
100module named ``example`` (with the supplied docstring). The method
101:func:`module::def` generates binding code that exposes the
102``add()`` function to Python. The last line returns the internal Python object
103associated with ``m`` to the Python interpreter.
104
105.. note::
106
107 Notice how little code was needed to expose our function to Python: all
108 details regarding the function's parameters and return value were
109 automatically inferred using template metaprogramming. This overall
110 approach and the used syntax are borrowed from Boost.Python, though the
111 underlying implementation is very different.
112
113pybind11 is a header-only-library, hence it is not necessary to link against
114any special libraries (other than Python itself). On Windows, use the CMake
115build file discussed in section :ref:`cmake`. On Linux and Mac OS, the above
116example can be compiled using the following command
117
118.. code-block:: bash
119
Wenzel Jakob06f56ee2016-04-28 16:25:24 +0200120 $ c++ -O3 -shared -std=c++11 -I <path-to-pybind11>/include `python-config --cflags --ldflags` example.cpp -o example.so
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200121
122In general, it is advisable to include several additional build parameters
123that can considerably reduce the size of the created binary. Refer to section
124:ref:`cmake` for a detailed example of a suitable cross-platform CMake-based
125build system.
126
127Assuming that the created file :file:`example.so` (:file:`example.pyd` on Windows)
128is located in the current directory, the following interactive Python session
129shows how to load and execute the example.
130
Wenzel Jakob99279f72016-06-03 11:19:29 +0200131.. code-block:: pycon
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200132
Wenzel Jakob93296692015-10-13 23:21:54 +0200133 $ python
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200134 Python 2.7.10 (default, Aug 22 2015, 20:33:39)
135 [GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.1)] on darwin
136 Type "help", "copyright", "credits" or "license" for more information.
137 >>> import example
138 >>> example.add(1, 2)
139 3L
Wenzel Jakob93296692015-10-13 23:21:54 +0200140 >>>
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200141
142.. _keyword_args:
143
144Keyword arguments
145=================
146
147With a simple modification code, it is possible to inform Python about the
148names of the arguments ("i" and "j" in this case).
149
150.. code-block:: cpp
151
152 m.def("add", &add, "A function which adds two numbers",
153 py::arg("i"), py::arg("j"));
154
155:class:`arg` is one of several special tag classes which can be used to pass
156metadata into :func:`module::def`. With this modified binding code, we can now
157call the function using keyword arguments, which is a more readable alternative
158particularly for functions taking many parameters:
159
Wenzel Jakob99279f72016-06-03 11:19:29 +0200160.. code-block:: pycon
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200161
162 >>> import example
163 >>> example.add(i=1, j=2)
164 3L
165
166The keyword names also appear in the function signatures within the documentation.
167
Wenzel Jakob99279f72016-06-03 11:19:29 +0200168.. code-block:: pycon
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200169
170 >>> help(example)
171
172 ....
173
174 FUNCTIONS
175 add(...)
Wenzel Jakob6eb11da2016-01-17 22:36:36 +0100176 Signature : (i: int, j: int) -> int
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200177
178 A function which adds two numbers
179
Dean Moldovanb3eadfa2016-06-03 23:48:31 +0200180A shorter notation for named arguments is also available:
181
182.. code-block:: cpp
183
184 // regular notation
185 m.def("add1", &add, py::arg("i"), py::arg("j"));
186 // shorthand
187 using namespace pybind11::literals;
188 m.def("add2", &add, "i"_a, "j"_a);
189
190The :var:`_a` suffix forms a C++11 literal which is equivalent to :class:`arg`.
191Note that the literal operator must first be made visible with the directive
192``using namespace pybind11::literals``. This does not bring in anything else
193from the ``pybind11`` namespace except for literals.
194
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200195.. _default_args:
196
197Default arguments
198=================
199
200Suppose now that the function to be bound has default arguments, e.g.:
201
202.. code-block:: cpp
203
204 int add(int i = 1, int j = 2) {
205 return i + j;
206 }
207
208Unfortunately, pybind11 cannot automatically extract these parameters, since they
209are not part of the function's type information. However, they are simple to specify
210using an extension of :class:`arg`:
211
212.. code-block:: cpp
213
214 m.def("add", &add, "A function which adds two numbers",
215 py::arg("i") = 1, py::arg("j") = 2);
216
217The default values also appear within the documentation.
218
Wenzel Jakob99279f72016-06-03 11:19:29 +0200219.. code-block:: pycon
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200220
221 >>> help(example)
222
223 ....
224
225 FUNCTIONS
226 add(...)
Wenzel Jakob6eb11da2016-01-17 22:36:36 +0100227 Signature : (i: int = 1, j: int = 2) -> int
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200228
229 A function which adds two numbers
230
Dean Moldovanb3eadfa2016-06-03 23:48:31 +0200231The shorthand notation is also available for default arguments:
232
233.. code-block:: cpp
234
235 // regular notation
236 m.def("add1", &add, py::arg("i") = 1, py::arg("j") = 2);
237 // shorthand
238 m.def("add2", &add, "i"_a=1, "j"_a=2);
239
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200240.. _supported_types:
241
242Supported data types
243====================
244
245The following basic data types are supported out of the box (some may require
246an additional extension header to be included). To pass other data structures
Wenzel Jakob93296692015-10-13 23:21:54 +0200247as arguments and return values, refer to the section on binding :ref:`classes`.
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200248
Wenzel Jakobf64feaf2016-04-28 14:33:45 +0200249+---------------------------------+--------------------------+-------------------------------+
250| Data type | Description | Header file |
251+=================================+==========================+===============================+
252| ``int8_t``, ``uint8_t`` | 8-bit integers | :file:`pybind11/pybind11.h` |
253+---------------------------------+--------------------------+-------------------------------+
254| ``int16_t``, ``uint16_t`` | 16-bit integers | :file:`pybind11/pybind11.h` |
255+---------------------------------+--------------------------+-------------------------------+
256| ``int32_t``, ``uint32_t`` | 32-bit integers | :file:`pybind11/pybind11.h` |
257+---------------------------------+--------------------------+-------------------------------+
258| ``int64_t``, ``uint64_t`` | 64-bit integers | :file:`pybind11/pybind11.h` |
259+---------------------------------+--------------------------+-------------------------------+
260| ``ssize_t``, ``size_t`` | Platform-dependent size | :file:`pybind11/pybind11.h` |
261+---------------------------------+--------------------------+-------------------------------+
262| ``float``, ``double`` | Floating point types | :file:`pybind11/pybind11.h` |
263+---------------------------------+--------------------------+-------------------------------+
264| ``bool`` | Two-state Boolean type | :file:`pybind11/pybind11.h` |
265+---------------------------------+--------------------------+-------------------------------+
266| ``char`` | Character literal | :file:`pybind11/pybind11.h` |
267+---------------------------------+--------------------------+-------------------------------+
268| ``wchar_t`` | Wide character literal | :file:`pybind11/pybind11.h` |
269+---------------------------------+--------------------------+-------------------------------+
270| ``const char *`` | UTF-8 string literal | :file:`pybind11/pybind11.h` |
271+---------------------------------+--------------------------+-------------------------------+
272| ``const wchar_t *`` | Wide string literal | :file:`pybind11/pybind11.h` |
273+---------------------------------+--------------------------+-------------------------------+
274| ``std::string`` | STL dynamic UTF-8 string | :file:`pybind11/pybind11.h` |
275+---------------------------------+--------------------------+-------------------------------+
276| ``std::wstring`` | STL dynamic wide string | :file:`pybind11/pybind11.h` |
277+---------------------------------+--------------------------+-------------------------------+
278| ``std::pair<T1, T2>`` | Pair of two custom types | :file:`pybind11/pybind11.h` |
279+---------------------------------+--------------------------+-------------------------------+
280| ``std::tuple<...>`` | Arbitrary tuple of types | :file:`pybind11/pybind11.h` |
281+---------------------------------+--------------------------+-------------------------------+
282| ``std::reference_wrapper<...>`` | Reference type wrapper | :file:`pybind11/pybind11.h` |
283+---------------------------------+--------------------------+-------------------------------+
284| ``std::complex<T>`` | Complex numbers | :file:`pybind11/complex.h` |
285+---------------------------------+--------------------------+-------------------------------+
286| ``std::array<T, Size>`` | STL static array | :file:`pybind11/stl.h` |
287+---------------------------------+--------------------------+-------------------------------+
288| ``std::vector<T>`` | STL dynamic array | :file:`pybind11/stl.h` |
289+---------------------------------+--------------------------+-------------------------------+
290| ``std::list<T>`` | STL linked list | :file:`pybind11/stl.h` |
291+---------------------------------+--------------------------+-------------------------------+
292| ``std::map<T1, T2>`` | STL ordered map | :file:`pybind11/stl.h` |
293+---------------------------------+--------------------------+-------------------------------+
294| ``std::unordered_map<T1, T2>`` | STL unordered map | :file:`pybind11/stl.h` |
295+---------------------------------+--------------------------+-------------------------------+
296| ``std::set<T>`` | STL ordered set | :file:`pybind11/stl.h` |
297+---------------------------------+--------------------------+-------------------------------+
298| ``std::unordered_set<T>`` | STL unordered set | :file:`pybind11/stl.h` |
299+---------------------------------+--------------------------+-------------------------------+
300| ``std::function<...>`` | STL polymorphic function | :file:`pybind11/functional.h` |
301+---------------------------------+--------------------------+-------------------------------+
Wenzel Jakob9e0a0562016-05-05 20:33:54 +0200302| ``Eigen::Matrix<...>`` | Dense Eigen matrices | :file:`pybind11/eigen.h` |
303+---------------------------------+--------------------------+-------------------------------+
304| ``Eigen::SparseMatrix<...>`` | Sparse Eigen matrices | :file:`pybind11/eigen.h` |
305+---------------------------------+--------------------------+-------------------------------+
Wenzel Jakob28f98aa2015-10-13 02:57:16 +0200306
307
308.. [#f1] In practice, implementation and binding code will generally be located
309 in separate files.