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.

283 lines
8.0 KiB

3 months ago
  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. Creating bindings for a simple function
  50. =======================================
  51. Let's start by creating Python bindings for an extremely simple function, which
  52. adds two numbers and returns their result:
  53. .. code-block:: cpp
  54. int add(int i, int j) {
  55. return i + j;
  56. }
  57. For simplicity [#f1]_, we'll put both this function and the binding code into
  58. a file named :file:`example.cpp` with the following contents:
  59. .. code-block:: cpp
  60. #include <pybind11/pybind11.h>
  61. int add(int i, int j) {
  62. return i + j;
  63. }
  64. PYBIND11_MODULE(example, m) {
  65. m.doc() = "pybind11 example plugin"; // optional module docstring
  66. m.def("add", &add, "A function which adds two numbers");
  67. }
  68. .. [#f1] In practice, implementation and binding code will generally be located
  69. in separate files.
  70. The :func:`PYBIND11_MODULE` macro creates a function that will be called when an
  71. ``import`` statement is issued from within Python. The module name (``example``)
  72. is given as the first macro argument (it should not be in quotes). The second
  73. argument (``m``) defines a variable of type :class:`py::module <module>` which
  74. is the main interface for creating bindings. The method :func:`module::def`
  75. generates binding code that exposes the ``add()`` function to Python.
  76. .. note::
  77. Notice how little code was needed to expose our function to Python: all
  78. details regarding the function's parameters and return value were
  79. automatically inferred using template metaprogramming. This overall
  80. approach and the used syntax are borrowed from Boost.Python, though the
  81. underlying implementation is very different.
  82. pybind11 is a header-only-library, hence it is not necessary to link against
  83. any special libraries (other than Python itself). On Windows, use the CMake
  84. build file discussed in section :ref:`cmake`. On Linux and Mac OS, the above
  85. example can be compiled using the following command
  86. .. code-block:: bash
  87. $ c++ -O3 -shared -std=c++11 -I <path-to-pybind11>/include `python-config --cflags --ldflags` example.cpp -o example.so
  88. In general, it is advisable to include several additional build parameters
  89. that can considerably reduce the size of the created binary. Refer to section
  90. :ref:`cmake` for a detailed example of a suitable cross-platform CMake-based
  91. build system.
  92. Assuming that the created file :file:`example.so` (:file:`example.pyd` on Windows)
  93. is located in the current directory, the following interactive Python session
  94. shows how to load and execute the example.
  95. .. code-block:: pycon
  96. $ python
  97. Python 2.7.10 (default, Aug 22 2015, 20:33:39)
  98. [GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.1)] on darwin
  99. Type "help", "copyright", "credits" or "license" for more information.
  100. >>> import example
  101. >>> example.add(1, 2)
  102. 3L
  103. >>>
  104. .. _keyword_args:
  105. Keyword arguments
  106. =================
  107. With a simple modification code, it is possible to inform Python about the
  108. names of the arguments ("i" and "j" in this case).
  109. .. code-block:: cpp
  110. m.def("add", &add, "A function which adds two numbers",
  111. py::arg("i"), py::arg("j"));
  112. :class:`arg` is one of several special tag classes which can be used to pass
  113. metadata into :func:`module::def`. With this modified binding code, we can now
  114. call the function using keyword arguments, which is a more readable alternative
  115. particularly for functions taking many parameters:
  116. .. code-block:: pycon
  117. >>> import example
  118. >>> example.add(i=1, j=2)
  119. 3L
  120. The keyword names also appear in the function signatures within the documentation.
  121. .. code-block:: pycon
  122. >>> help(example)
  123. ....
  124. FUNCTIONS
  125. add(...)
  126. Signature : (i: int, j: int) -> int
  127. A function which adds two numbers
  128. A shorter notation for named arguments is also available:
  129. .. code-block:: cpp
  130. // regular notation
  131. m.def("add1", &add, py::arg("i"), py::arg("j"));
  132. // shorthand
  133. using namespace pybind11::literals;
  134. m.def("add2", &add, "i"_a, "j"_a);
  135. The :var:`_a` suffix forms a C++11 literal which is equivalent to :class:`arg`.
  136. Note that the literal operator must first be made visible with the directive
  137. ``using namespace pybind11::literals``. This does not bring in anything else
  138. from the ``pybind11`` namespace except for literals.
  139. .. _default_args:
  140. Default arguments
  141. =================
  142. Suppose now that the function to be bound has default arguments, e.g.:
  143. .. code-block:: cpp
  144. int add(int i = 1, int j = 2) {
  145. return i + j;
  146. }
  147. Unfortunately, pybind11 cannot automatically extract these parameters, since they
  148. are not part of the function's type information. However, they are simple to specify
  149. using an extension of :class:`arg`:
  150. .. code-block:: cpp
  151. m.def("add", &add, "A function which adds two numbers",
  152. py::arg("i") = 1, py::arg("j") = 2);
  153. The default values also appear within the documentation.
  154. .. code-block:: pycon
  155. >>> help(example)
  156. ....
  157. FUNCTIONS
  158. add(...)
  159. Signature : (i: int = 1, j: int = 2) -> int
  160. A function which adds two numbers
  161. The shorthand notation is also available for default arguments:
  162. .. code-block:: cpp
  163. // regular notation
  164. m.def("add1", &add, py::arg("i") = 1, py::arg("j") = 2);
  165. // shorthand
  166. m.def("add2", &add, "i"_a=1, "j"_a=2);
  167. Exporting variables
  168. ===================
  169. To expose a value from C++, use the ``attr`` function to register it in a
  170. module as shown below. Built-in types and general objects (more on that later)
  171. are automatically converted when assigned as attributes, and can be explicitly
  172. converted using the function ``py::cast``.
  173. .. code-block:: cpp
  174. PYBIND11_MODULE(example, m) {
  175. m.attr("the_answer") = 42;
  176. py::object world = py::cast("World");
  177. m.attr("what") = world;
  178. }
  179. These are then accessible from Python:
  180. .. code-block:: pycon
  181. >>> import example
  182. >>> example.the_answer
  183. 42
  184. >>> example.what
  185. 'World'
  186. .. _supported_types:
  187. Supported data types
  188. ====================
  189. A large number of data types are supported out of the box and can be used
  190. seamlessly as functions arguments, return values or with ``py::cast`` in general.
  191. For a full overview, see the :doc:`advanced/cast/index` section.