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.

243 lines
9.8 KiB

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