pythonpybind11

Building pybind11 example successfully, but still got ImportError


I'm trying to use pybind for the first time. I tried different ways, but eventually I decided to go with the 'official' PyBind11 example.

I did the following steps:

The last line printed by the script is: cmake_example.vcxproj -> D:\Git\pybindtest\build\lib.win-amd64-cpython-311\cmake_example.cp311-win_amd64.pyd, so I believe everything is built successfully.

However, when trying to run .\cmake_example\tests\test_basic.py, I'm getting a standard error:

Traceback (most recent call last):
  File "D:\Git\pybindtest\cmake_example\tests\test_basic.py", line 1, in <module>
    import cmake_example as m
ImportError: dynamic module does not define module export function (PyInit_cmake_example)

I got the same error when manually type import cmake_example in Python console.


Solution

    1. Check CMakeLists.txt: Ensure your CMakeLists.txt includes the proper PyBind11 configuration:

      cmake_minimum_required(VERSION 3.12)
      project(cmake_example)
      
      set(CMAKE_CXX_STANDARD 14)
      find_package(pybind11 REQUIRED)
      
      pybind11_add_module(cmake_example src/main.cpp)
      
    2. Rebuild the Project: After confirming the CMakeLists.txt is correct, rebuild the project by running:

      python setup.py build
      
    3. Ensure Correct Python Version: Verify that the Python version used in your virtual environment matches the one used during the build process (python --version).

    4. Check the Build Output: After rebuilding, check the output directory for the .pyd file (e.g., cmake_example.cp311-win_amd64.pyd) and make sure it's in your Python path (e.g., the same directory as the test script). Then run the test again.