PageRenderTime 54ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/include/external/pybind11/docs/faq.rst

https://gitlab.com/kattyrats1/PaGMOreborn
ReStructuredText | 215 lines | 153 code | 62 blank | 0 comment | 0 complexity | a15e39d751c3fb1cee8e20f0ccf0f5cd MD5 | raw file
  1. Frequently asked questions
  2. ##########################
  3. "ImportError: dynamic module does not define init function"
  4. ===========================================================
  5. 1. Make sure that the name specified in ``pybind::module`` and
  6. ``PYBIND11_PLUGIN`` is consistent and identical to the filename of the
  7. extension library. The latter should not contain any extra prefixes (e.g.
  8. ``test.so`` instead of ``libtest.so``).
  9. 2. If the above did not fix your issue, then you are likely using an
  10. incompatible version of Python (for instance, the extension library was
  11. compiled against Python 2, while the interpreter is running on top of some
  12. version of Python 3, or vice versa)
  13. "Symbol not found: ``__Py_ZeroStruct`` / ``_PyInstanceMethod_Type``"
  14. ========================================================================
  15. See item 2 of the first answer.
  16. The Python interpreter immediately crashes when importing my module
  17. ===================================================================
  18. See item 2 of the first answer.
  19. CMake doesn't detect the right Python version, or it finds mismatched interpreter and library versions
  20. ======================================================================================================
  21. The Python detection logic of CMake is flawed and can sometimes fail to find
  22. the desired Python version, or it chooses mismatched interpreter and library
  23. versions. A longer discussion is available on the pybind11 issue tracker
  24. [#f1]_, though this is ultimately not a pybind11 issue.
  25. To force the build system to choose a particular version, delete CMakeCache.txt
  26. and then invoke CMake as follows:
  27. .. code-block:: bash
  28. cmake -DPYTHON_EXECUTABLE:FILEPATH=<...> \
  29. -DPYTHON_LIBRARY:FILEPATH=<...> \
  30. -DPYTHON_INCLUDE_DIR:PATH=<...> .
  31. .. [#f1] http://github.com/pybind/pybind11/issues/99
  32. Limitations involving reference arguments
  33. =========================================
  34. In C++, it's fairly common to pass arguments using mutable references or
  35. mutable pointers, which allows both read and write access to the value
  36. supplied by the caller. This is sometimes done for efficiency reasons, or to
  37. realize functions that have multiple return values. Here are two very basic
  38. examples:
  39. .. code-block:: cpp
  40. void increment(int &i) { i++; }
  41. void increment_ptr(int *i) { (*i)++; }
  42. In Python, all arguments are passed by reference, so there is no general
  43. issue in binding such code from Python.
  44. However, certain basic Python types (like ``str``, ``int``, ``bool``,
  45. ``float``, etc.) are **immutable**. This means that the following attempt
  46. to port the function to Python doesn't have the same effect on the value
  47. provided by the caller -- in fact, it does nothing at all.
  48. .. code-block:: python
  49. def increment(i):
  50. i += 1 # nope..
  51. pybind11 is also affected by such language-level conventions, which means that
  52. binding ``increment`` or ``increment_ptr`` will also create Python functions
  53. that don't modify their arguments.
  54. Although inconvenient, one workaround is to encapsulate the immutable types in
  55. a custom type that does allow modifications.
  56. An other alternative involves binding a small wrapper lambda function that
  57. returns a tuple with all output arguments (see the remainder of the
  58. documentation for examples on binding lambda functions). An example:
  59. .. code-block:: cpp
  60. int foo(int &i) { i++; return 123; }
  61. and the binding code
  62. .. code-block:: cpp
  63. m.def("foo", [](int i) { int rv = foo(i); return std::make_tuple(rv, i); });
  64. How can I reduce the build time?
  65. ================================
  66. It's good practice to split binding code over multiple files, as is done in
  67. the included file :file:`example/example.cpp`.
  68. .. code-block:: cpp
  69. void init_ex1(py::module &);
  70. void init_ex2(py::module &);
  71. /* ... */
  72. PYBIND11_PLUGIN(example) {
  73. py::module m("example", "pybind example plugin");
  74. init_ex1(m);
  75. init_ex2(m);
  76. /* ... */
  77. return m.ptr();
  78. }
  79. The various ``init_ex`` functions should be contained in separate files that
  80. can be compiled independently from another. Following this approach will
  81. 1. reduce memory requirements per compilation unit.
  82. 2. enable parallel builds (if desired).
  83. 3. allow for faster incremental builds. For instance, when a single class
  84. definiton is changed, only a subset of the binding code will generally need
  85. to be recompiled.
  86. How can I create smaller binaries?
  87. ==================================
  88. To do its job, pybind11 extensively relies on a programming technique known as
  89. *template metaprogramming*, which is a way of performing computation at compile
  90. time using type information. Template metaprogamming usually instantiates code
  91. involving significant numbers of deeply nested types that are either completely
  92. removed or reduced to just a few instrutions during the compiler's optimization
  93. phase. However, due to the nested nature of these types, the resulting symbol
  94. names in the compiled extension library can be extremely long. For instance,
  95. the included test suite contains the following symbol:
  96. .. only:: html
  97. .. code-block:: none
  98. __ZN8pybind1112cpp_functionC1Iv8Example2JRNSt3__16vectorINS3_12basic_stringIwNS3_11char_traitsIwEENS3_9allocatorIwEEEENS8_ISA_EEEEEJNS_4nameENS_7siblingENS_9is_methodEA28_cEEEMT0_FT_DpT1_EDpRKT2_
  99. .. only:: not html
  100. .. code-block:: cpp
  101. __ZN8pybind1112cpp_functionC1Iv8Example2JRNSt3__16vectorINS3_12basic_stringIwNS3_11char_traitsIwEENS3_9allocatorIwEEEENS8_ISA_EEEEEJNS_4nameENS_7siblingENS_9is_methodEA28_cEEEMT0_FT_DpT1_EDpRKT2_
  102. which is the mangled form of the following function type:
  103. .. code-block:: cpp
  104. pybind11::cpp_function::cpp_function<void, Example2, std::__1::vector<std::__1::basic_string<wchar_t, std::__1::char_traits<wchar_t>, std::__1::allocator<wchar_t> >, std::__1::allocator<std::__1::basic_string<wchar_t, std::__1::char_traits<wchar_t>, std::__1::allocator<wchar_t> > > >&, pybind11::name, pybind11::sibling, pybind11::is_method, char [28]>(void (Example2::*)(std::__1::vector<std::__1::basic_string<wchar_t, std::__1::char_traits<wchar_t>, std::__1::allocator<wchar_t> >, std::__1::allocator<std::__1::basic_string<wchar_t, std::__1::char_traits<wchar_t>, std::__1::allocator<wchar_t> > > >&), pybind11::name const&, pybind11::sibling const&, pybind11::is_method const&, char const (&) [28])
  105. The memory needed to store just the mangled name of this function (196 bytes)
  106. is larger than the actual piece of code (111 bytes) it represents! On the other
  107. hand, it's silly to even give this function a name -- after all, it's just a
  108. tiny cog in a bigger piece of machinery that is not exposed to the outside
  109. world. So we'll generally only want to export symbols for those functions which
  110. are actually called from the outside.
  111. This can be achieved by specifying the parameter ``-fvisibility=hidden`` to GCC
  112. and Clang, which sets the default symbol visibility to *hidden*. It's best to
  113. do this only for release builds, since the symbol names can be helpful in
  114. debugging sessions. On Visual Studio, symbols are already hidden by default, so
  115. nothing needs to be done there. Needless to say, this has a tremendous impact
  116. on the final binary size of the resulting extension library.
  117. Another aspect that can require a fair bit of code are function signature
  118. descriptions. pybind11 automatically generates human-readable function
  119. signatures for docstrings, e.g.:
  120. .. code-block:: none
  121. | __init__(...)
  122. | __init__(*args, **kwargs)
  123. | Overloaded function.
  124. |
  125. | 1. __init__(example.Example1) -> NoneType
  126. |
  127. | Docstring for overload #1 goes here
  128. |
  129. | 2. __init__(example.Example1, int) -> NoneType
  130. |
  131. | Docstring for overload #2 goes here
  132. |
  133. | 3. __init__(example.Example1, example.Example1) -> NoneType
  134. |
  135. | Docstring for overload #3 goes here
  136. In C++11 mode, these are generated at run time using string concatenation,
  137. which can amount to 10-20% of the size of the resulting binary. If you can,
  138. enable C++14 language features (using ``-std=c++14`` for GCC/Clang), in which
  139. case signatures are efficiently pre-generated at compile time. Unfortunately,
  140. Visual Studio's C++14 support (``constexpr``) is not good enough as of April
  141. 2016, so it always uses the more expensive run-time approach.
  142. Working with ancient Visual Studio 2009 builds on Windows
  143. =========================================================
  144. The official Windows distributions of Python are compiled using truly
  145. ancient versions of Visual Studio that lack good C++11 support. Some users
  146. implicitly assume that it would be impossible to load a plugin built with
  147. Visual Studio 2015 into a Python distribution that was compiled using Visual
  148. Studio 2009. However, no such issue exists: it's perfectly legitimate to
  149. interface DLLs that are built with different compilers and/or C libraries.
  150. Common gotchas to watch out for involve not ``free()``-ing memory region
  151. that that were ``malloc()``-ed in another shared library, using data
  152. structures with incompatible ABIs, and so on. pybind11 is very careful not
  153. to make these types of mistakes.