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.

251 lines
10 KiB

  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. "SystemError: dynamic module not initialized properly"
  17. ======================================================
  18. See item 2 of the first answer.
  19. The Python interpreter immediately crashes when importing my module
  20. ===================================================================
  21. See item 2 of the first answer.
  22. CMake doesn't detect the right Python version
  23. =============================================
  24. The CMake-based build system will try to automatically detect the installed
  25. version of Python and link against that. When this fails, or when there are
  26. multiple versions of Python and it finds the wrong one, delete
  27. ``CMakeCache.txt`` and then invoke CMake as follows:
  28. .. code-block:: bash
  29. cmake -DPYTHON_EXECUTABLE:FILEPATH=<path-to-python-executable> .
  30. Limitations involving reference arguments
  31. =========================================
  32. In C++, it's fairly common to pass arguments using mutable references or
  33. mutable pointers, which allows both read and write access to the value
  34. supplied by the caller. This is sometimes done for efficiency reasons, or to
  35. realize functions that have multiple return values. Here are two very basic
  36. examples:
  37. .. code-block:: cpp
  38. void increment(int &i) { i++; }
  39. void increment_ptr(int *i) { (*i)++; }
  40. In Python, all arguments are passed by reference, so there is no general
  41. issue in binding such code from Python.
  42. However, certain basic Python types (like ``str``, ``int``, ``bool``,
  43. ``float``, etc.) are **immutable**. This means that the following attempt
  44. to port the function to Python doesn't have the same effect on the value
  45. provided by the caller -- in fact, it does nothing at all.
  46. .. code-block:: python
  47. def increment(i):
  48. i += 1 # nope..
  49. pybind11 is also affected by such language-level conventions, which means that
  50. binding ``increment`` or ``increment_ptr`` will also create Python functions
  51. that don't modify their arguments.
  52. Although inconvenient, one workaround is to encapsulate the immutable types in
  53. a custom type that does allow modifications.
  54. An other alternative involves binding a small wrapper lambda function that
  55. returns a tuple with all output arguments (see the remainder of the
  56. documentation for examples on binding lambda functions). An example:
  57. .. code-block:: cpp
  58. int foo(int &i) { i++; return 123; }
  59. and the binding code
  60. .. code-block:: cpp
  61. m.def("foo", [](int i) { int rv = foo(i); return std::make_tuple(rv, i); });
  62. How can I reduce the build time?
  63. ================================
  64. It's good practice to split binding code over multiple files, as in the
  65. following example:
  66. :file:`example.cpp`:
  67. .. code-block:: cpp
  68. void init_ex1(py::module &);
  69. void init_ex2(py::module &);
  70. /* ... */
  71. PYBIND11_PLUGIN(example) {
  72. py::module m("example", "pybind example plugin");
  73. init_ex1(m);
  74. init_ex2(m);
  75. /* ... */
  76. return m.ptr();
  77. }
  78. :file:`ex1.cpp`:
  79. .. code-block:: cpp
  80. void init_ex1(py::module &m) {
  81. m.def("add", [](int a, int b) { return a + b; });
  82. }
  83. :file:`ex2.cpp`:
  84. .. code-block:: cpp
  85. void init_ex1(py::module &m) {
  86. m.def("sub", [](int a, int b) { return a - b; });
  87. }
  88. :command:`python`:
  89. .. code-block:: pycon
  90. >>> import example
  91. >>> example.add(1, 2)
  92. 3
  93. >>> example.sub(1, 1)
  94. 0
  95. As shown above, the various ``init_ex`` functions should be contained in
  96. separate files that can be compiled independently from one another, and then
  97. linked together into the same final shared object. Following this approach
  98. will:
  99. 1. reduce memory requirements per compilation unit.
  100. 2. enable parallel builds (if desired).
  101. 3. allow for faster incremental builds. For instance, when a single class
  102. definition is changed, only a subset of the binding code will generally need
  103. to be recompiled.
  104. "recursive template instantiation exceeded maximum depth of 256"
  105. ================================================================
  106. If you receive an error about excessive recursive template evaluation, try
  107. specifying a larger value, e.g. ``-ftemplate-depth=1024`` on GCC/Clang. The
  108. culprit is generally the generation of function signatures at compile time
  109. using C++14 template metaprogramming.
  110. How can I create smaller binaries?
  111. ==================================
  112. To do its job, pybind11 extensively relies on a programming technique known as
  113. *template metaprogramming*, which is a way of performing computation at compile
  114. time using type information. Template metaprogamming usually instantiates code
  115. involving significant numbers of deeply nested types that are either completely
  116. removed or reduced to just a few instructions during the compiler's optimization
  117. phase. However, due to the nested nature of these types, the resulting symbol
  118. names in the compiled extension library can be extremely long. For instance,
  119. the included test suite contains the following symbol:
  120. .. only:: html
  121. .. code-block:: none
  122. _​_​Z​N​8​p​y​b​i​n​d​1​1​1​2​c​p​p​_​f​u​n​c​t​i​o​n​C​1​I​v​8​E​x​a​m​p​l​e​2​J​R​N​S​t​3​_​_​1​6​v​e​c​t​o​r​I​N​S​3​_​1​2​b​a​s​i​c​_​s​t​r​i​n​g​I​w​N​S​3​_​1​1​c​h​a​r​_​t​r​a​i​t​s​I​w​E​E​N​S​3​_​9​a​l​l​o​c​a​t​o​r​I​w​E​E​E​E​N​S​8​_​I​S​A​_​E​E​E​E​E​J​N​S​_​4​n​a​m​e​E​N​S​_​7​s​i​b​l​i​n​g​E​N​S​_​9​i​s​_​m​e​t​h​o​d​E​A​2​8​_​c​E​E​E​M​T​0​_​F​T​_​D​p​T​1​_​E​D​p​R​K​T​2​_
  123. .. only:: not html
  124. .. code-block:: cpp
  125. __ZN8pybind1112cpp_functionC1Iv8Example2JRNSt3__16vectorINS3_12basic_stringIwNS3_11char_traitsIwEENS3_9allocatorIwEEEENS8_ISA_EEEEEJNS_4nameENS_7siblingENS_9is_methodEA28_cEEEMT0_FT_DpT1_EDpRKT2_
  126. which is the mangled form of the following function type:
  127. .. code-block:: cpp
  128. 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])
  129. The memory needed to store just the mangled name of this function (196 bytes)
  130. is larger than the actual piece of code (111 bytes) it represents! On the other
  131. hand, it's silly to even give this function a name -- after all, it's just a
  132. tiny cog in a bigger piece of machinery that is not exposed to the outside
  133. world. So we'll generally only want to export symbols for those functions which
  134. are actually called from the outside.
  135. This can be achieved by specifying the parameter ``-fvisibility=hidden`` to GCC
  136. and Clang, which sets the default symbol visibility to *hidden*. It's best to
  137. do this only for release builds, since the symbol names can be helpful in
  138. debugging sessions. On Visual Studio, symbols are already hidden by default, so
  139. nothing needs to be done there. Needless to say, this has a tremendous impact
  140. on the final binary size of the resulting extension library.
  141. Another aspect that can require a fair bit of code are function signature
  142. descriptions. pybind11 automatically generates human-readable function
  143. signatures for docstrings, e.g.:
  144. .. code-block:: none
  145. | __init__(...)
  146. | __init__(*args, **kwargs)
  147. | Overloaded function.
  148. |
  149. | 1. __init__(example.Example1) -> NoneType
  150. |
  151. | Docstring for overload #1 goes here
  152. |
  153. | 2. __init__(example.Example1, int) -> NoneType
  154. |
  155. | Docstring for overload #2 goes here
  156. |
  157. | 3. __init__(example.Example1, example.Example1) -> NoneType
  158. |
  159. | Docstring for overload #3 goes here
  160. In C++11 mode, these are generated at run time using string concatenation,
  161. which can amount to 10-20% of the size of the resulting binary. If you can,
  162. enable C++14 language features (using ``-std=c++14`` for GCC/Clang), in which
  163. case signatures are efficiently pre-generated at compile time. Unfortunately,
  164. Visual Studio's C++14 support (``constexpr``) is not good enough as of April
  165. 2016, so it always uses the more expensive run-time approach.
  166. Working with ancient Visual Studio 2009 builds on Windows
  167. =========================================================
  168. The official Windows distributions of Python are compiled using truly
  169. ancient versions of Visual Studio that lack good C++11 support. Some users
  170. implicitly assume that it would be impossible to load a plugin built with
  171. Visual Studio 2015 into a Python distribution that was compiled using Visual
  172. Studio 2009. However, no such issue exists: it's perfectly legitimate to
  173. interface DLLs that are built with different compilers and/or C libraries.
  174. Common gotchas to watch out for involve not ``free()``-ing memory region
  175. that that were ``malloc()``-ed in another shared library, using data
  176. structures with incompatible ABIs, and so on. pybind11 is very careful not
  177. to make these types of mistakes.