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.

289 lines
8.1 KiB

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