basics.rst 8.5 KB

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