basics.rst 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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 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 macOS, 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. mkdir build
  17. cd build
  18. cmake ..
  19. make check -j 4
  20. The last line will both compile and run the tests.
  21. Windows
  22. -------
  23. On Windows, only **Visual Studio 2015** and newer are supported since pybind11 relies
  24. on various C++11 language features that break older versions of Visual Studio.
  25. .. Note::
  26. To use the C++17 in Visual Studio 2017 (MSVC 14.1), pybind11 requires the flag
  27. ``/permissive-`` to be passed to the compiler `to enforce standard conformance`_. When
  28. building with Visual Studio 2019, this is not strictly necessary, but still advised.
  29. .. _`to enforce standard conformance`: https://docs.microsoft.com/en-us/cpp/build/reference/permissive-standards-conformance?view=vs-2017
  30. To compile and run the tests:
  31. .. code-block:: batch
  32. mkdir build
  33. cd build
  34. cmake ..
  35. cmake --build . --config Release --target check
  36. This will create a Visual Studio project, compile and run the target, all from the
  37. command line.
  38. .. Note::
  39. If all tests fail, make sure that the Python binary and the testcases are compiled
  40. for the same processor type and bitness (i.e. either **i386** or **x86_64**). You
  41. can specify **x86_64** as the target architecture for the generated Visual Studio
  42. project using ``cmake -A x64 ..``.
  43. .. seealso::
  44. Advanced users who are already familiar with Boost.Python may want to skip
  45. the tutorial and look at the test cases in the :file:`tests` directory,
  46. which exercise all features of pybind11.
  47. Header and namespace conventions
  48. ================================
  49. For brevity, all code examples assume that the following two lines are present:
  50. .. code-block:: cpp
  51. #include <pybind11/pybind11.h>
  52. namespace py = pybind11;
  53. Some features may require additional headers, but those will be specified as needed.
  54. .. _simple_example:
  55. Creating bindings for a simple function
  56. =======================================
  57. Let's start by creating Python bindings for an extremely simple function, which
  58. adds two numbers and returns their result:
  59. .. code-block:: cpp
  60. int add(int i, int j) {
  61. return i + j;
  62. }
  63. For simplicity [#f1]_, we'll put both this function and the binding code into
  64. a file named :file:`example.cpp` with the following contents:
  65. .. code-block:: cpp
  66. #include <pybind11/pybind11.h>
  67. int add(int i, int j) {
  68. return i + j;
  69. }
  70. PYBIND11_MODULE(example, m) {
  71. m.doc() = "pybind11 example plugin"; // optional module docstring
  72. m.def("add", &add, "A function which adds two numbers");
  73. }
  74. .. [#f1] In practice, implementation and binding code will generally be located
  75. in separate files.
  76. The :func:`PYBIND11_MODULE` macro creates a function that will be called when an
  77. ``import`` statement is issued from within Python. The module name (``example``)
  78. is given as the first macro argument (it should not be in quotes). The second
  79. argument (``m``) defines a variable of type :class:`py::module_ <module>` which
  80. is the main interface for creating bindings. The method :func:`module_::def`
  81. generates binding code that exposes the ``add()`` function to Python.
  82. .. note::
  83. Notice how little code was needed to expose our function to Python: all
  84. details regarding the function's parameters and return value were
  85. automatically inferred using template metaprogramming. This overall
  86. approach and the used syntax are borrowed from Boost.Python, though the
  87. underlying implementation is very different.
  88. pybind11 is a header-only library, hence it is not necessary to link against
  89. any special libraries and there are no intermediate (magic) translation steps.
  90. On Linux, the above example can be compiled using the following command:
  91. .. code-block:: bash
  92. $ c++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes) example.cpp -o example$(python3-config --extension-suffix)
  93. .. note::
  94. If you used :ref:`include_as_a_submodule` to get the pybind11 source, then
  95. use ``$(python3-config --includes) -Iextern/pybind11/include`` instead of
  96. ``$(python3 -m pybind11 --includes)`` in the above compilation, as
  97. explained in :ref:`building_manually`.
  98. For more details on the required compiler flags on Linux and macOS, see
  99. :ref:`building_manually`. For complete cross-platform compilation instructions,
  100. refer to the :ref:`compiling` page.
  101. The `python_example`_ and `cmake_example`_ repositories are also a good place
  102. to start. They are both complete project examples with cross-platform build
  103. systems. The only difference between the two is that `python_example`_ uses
  104. Python's ``setuptools`` to build the module, while `cmake_example`_ uses CMake
  105. (which may be preferable for existing C++ projects).
  106. .. _python_example: https://github.com/pybind/python_example
  107. .. _cmake_example: https://github.com/pybind/cmake_example
  108. Building the above C++ code will produce a binary module file that can be
  109. imported to Python. Assuming that the compiled module is located in the
  110. current directory, the following interactive Python session shows how to
  111. load and execute the example:
  112. .. code-block:: pycon
  113. $ python
  114. Python 2.7.10 (default, Aug 22 2015, 20:33:39)
  115. [GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.1)] on darwin
  116. Type "help", "copyright", "credits" or "license" for more information.
  117. >>> import example
  118. >>> example.add(1, 2)
  119. 3L
  120. >>>
  121. .. _keyword_args:
  122. Keyword arguments
  123. =================
  124. With a simple code modification, it is possible to inform Python about the
  125. names of the arguments ("i" and "j" in this case).
  126. .. code-block:: cpp
  127. m.def("add", &add, "A function which adds two numbers",
  128. py::arg("i"), py::arg("j"));
  129. :class:`arg` is one of several special tag classes which can be used to pass
  130. metadata into :func:`module_::def`. With this modified binding code, we can now
  131. call the function using keyword arguments, which is a more readable alternative
  132. particularly for functions taking many parameters:
  133. .. code-block:: pycon
  134. >>> import example
  135. >>> example.add(i=1, j=2)
  136. 3L
  137. The keyword names also appear in the function signatures within the documentation.
  138. .. code-block:: pycon
  139. >>> help(example)
  140. ....
  141. FUNCTIONS
  142. add(...)
  143. Signature : (i: int, j: int) -> int
  144. A function which adds two numbers
  145. A shorter notation for named arguments is also available:
  146. .. code-block:: cpp
  147. // regular notation
  148. m.def("add1", &add, py::arg("i"), py::arg("j"));
  149. // shorthand
  150. using namespace pybind11::literals;
  151. m.def("add2", &add, "i"_a, "j"_a);
  152. The :var:`_a` suffix forms a C++11 literal which is equivalent to :class:`arg`.
  153. Note that the literal operator must first be made visible with the directive
  154. ``using namespace pybind11::literals``. This does not bring in anything else
  155. from the ``pybind11`` namespace except for literals.
  156. .. _default_args:
  157. Default arguments
  158. =================
  159. Suppose now that the function to be bound has default arguments, e.g.:
  160. .. code-block:: cpp
  161. int add(int i = 1, int j = 2) {
  162. return i + j;
  163. }
  164. Unfortunately, pybind11 cannot automatically extract these parameters, since they
  165. are not part of the function's type information. However, they are simple to specify
  166. using an extension of :class:`arg`:
  167. .. code-block:: cpp
  168. m.def("add", &add, "A function which adds two numbers",
  169. py::arg("i") = 1, py::arg("j") = 2);
  170. The default values also appear within the documentation.
  171. .. code-block:: pycon
  172. >>> help(example)
  173. ....
  174. FUNCTIONS
  175. add(...)
  176. Signature : (i: int = 1, j: int = 2) -> int
  177. A function which adds two numbers
  178. The shorthand notation is also available for default arguments:
  179. .. code-block:: cpp
  180. // regular notation
  181. m.def("add1", &add, py::arg("i") = 1, py::arg("j") = 2);
  182. // shorthand
  183. m.def("add2", &add, "i"_a=1, "j"_a=2);
  184. Exporting variables
  185. ===================
  186. To expose a value from C++, use the ``attr`` function to register it in a
  187. module as shown below. Built-in types and general objects (more on that later)
  188. are automatically converted when assigned as attributes, and can be explicitly
  189. converted using the function ``py::cast``.
  190. .. code-block:: cpp
  191. PYBIND11_MODULE(example, m) {
  192. m.attr("the_answer") = 42;
  193. py::object world = py::cast("World");
  194. m.attr("what") = world;
  195. }
  196. These are then accessible from Python:
  197. .. code-block:: pycon
  198. >>> import example
  199. >>> example.the_answer
  200. 42
  201. >>> example.what
  202. 'World'
  203. .. _supported_types:
  204. Supported data types
  205. ====================
  206. A large number of data types are supported out of the box and can be used
  207. seamlessly as functions arguments, return values or with ``py::cast`` in general.
  208. For a full overview, see the :doc:`advanced/cast/index` section.