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.

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