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.

280 lines
11 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 --libs` 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:: python
  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:: python
  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:: python
  116. >>> help(example)
  117. ....
  118. FUNCTIONS
  119. add(...)
  120. Signature : (i: int, j: int) -> int
  121. A function which adds two numbers
  122. .. _default_args:
  123. Default arguments
  124. =================
  125. Suppose now that the function to be bound has default arguments, e.g.:
  126. .. code-block:: cpp
  127. int add(int i = 1, int j = 2) {
  128. return i + j;
  129. }
  130. Unfortunately, pybind11 cannot automatically extract these parameters, since they
  131. are not part of the function's type information. However, they are simple to specify
  132. using an extension of :class:`arg`:
  133. .. code-block:: cpp
  134. m.def("add", &add, "A function which adds two numbers",
  135. py::arg("i") = 1, py::arg("j") = 2);
  136. The default values also appear within the documentation.
  137. .. code-block:: python
  138. >>> help(example)
  139. ....
  140. FUNCTIONS
  141. add(...)
  142. Signature : (i: int = 1, j: int = 2) -> int
  143. A function which adds two numbers
  144. .. _supported_types:
  145. Supported data types
  146. ====================
  147. The following basic data types are supported out of the box (some may require
  148. an additional extension header to be included). To pass other data structures
  149. as arguments and return values, refer to the section on binding :ref:`classes`.
  150. +----------------------------+--------------------------+-----------------------+
  151. | Data type | Description | Header file |
  152. +============================+==========================+=======================+
  153. | int8_t, uint8_t | 8-bit integers | pybind11/pybind11.h |
  154. +----------------------------+--------------------------+-----------------------+
  155. | int16_t, uint16_t | 16-bit integers | pybind11/pybind11.h |
  156. +----------------------------+--------------------------+-----------------------+
  157. | int32_t, uint32_t | 32-bit integers | pybind11/pybind11.h |
  158. +----------------------------+--------------------------+-----------------------+
  159. | int64_t, uint64_t | 64-bit integers | pybind11/pybind11.h |
  160. +----------------------------+--------------------------+-----------------------+
  161. | ssize_t, size_t | Platform-dependent size | pybind11/pybind11.h |
  162. +----------------------------+--------------------------+-----------------------+
  163. | float, double | Floating point types | pybind11/pybind11.h |
  164. +----------------------------+--------------------------+-----------------------+
  165. | bool | Two-state Boolean type | pybind11/pybind11.h |
  166. +----------------------------+--------------------------+-----------------------+
  167. | char | Character literal | pybind11/pybind11.h |
  168. +----------------------------+--------------------------+-----------------------+
  169. | wchar_t | Wide character literal | pybind11/pybind11.h |
  170. +----------------------------+--------------------------+-----------------------+
  171. | const char * | UTF-8 string literal | pybind11/pybind11.h |
  172. +----------------------------+--------------------------+-----------------------+
  173. | const wchar_t * | Wide string literal | pybind11/pybind11.h |
  174. +----------------------------+--------------------------+-----------------------+
  175. | std::string | STL dynamic UTF-8 string | pybind11/pybind11.h |
  176. +----------------------------+--------------------------+-----------------------+
  177. | std::wstring | STL dynamic wide string | pybind11/pybind11.h |
  178. +----------------------------+--------------------------+-----------------------+
  179. | std::pair<T1, T2> | Pair of two custom types | pybind11/pybind11.h |
  180. +----------------------------+--------------------------+-----------------------+
  181. | std::tuple<....> | Arbitrary tuple of types | pybind11/pybind11.h |
  182. +----------------------------+--------------------------+-----------------------+
  183. | std::complex<T> | Complex numbers | pybind11/complex.h |
  184. +----------------------------+--------------------------+-----------------------+
  185. | std::array<T, Size> | STL static array | pybind11/stl.h |
  186. +----------------------------+--------------------------+-----------------------+
  187. | std::vector<T> | STL dynamic array | pybind11/stl.h |
  188. +----------------------------+--------------------------+-----------------------+
  189. | std::list<T> | STL linked list | pybind11/stl.h |
  190. +----------------------------+--------------------------+-----------------------+
  191. | std::map<T1, T2> | STL ordered map | pybind11/stl.h |
  192. +----------------------------+--------------------------+-----------------------+
  193. | std::unordered_map<T1, T2> | STL unordered map | pybind11/stl.h |
  194. +----------------------------+--------------------------+-----------------------+
  195. | std::set<T> | STL ordered set | pybind11/stl.h |
  196. +----------------------------+--------------------------+-----------------------+
  197. | std::unordered_set<T> | STL unordered set | pybind11/stl.h |
  198. +----------------------------+--------------------------+-----------------------+
  199. | std::function<...> | STL polymorphic function | pybind11/functional.h |
  200. +----------------------------+--------------------------+-----------------------+
  201. .. [#f1] In practice, implementation and binding code will generally be located
  202. in separate files.