You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

309 lines
13 KiB

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