Search code examples
pythonc++boostboost-python

Python cannot find Boost.Python module


I try to create a simple C++ module for python with Boost, but python gives me ModuleNotFoundError: No module named 'MyLib'.
The .py file is in the same location as MyLib.dll.

UPD: if i change dll to pyd or replace add_library(MyLib MODULE MyLib.cpp) with PYTHON_ADD_MODULE(MyLib MyLib.cpp) I get another error: ImportError: DLL load failed while importing MyLib: The specified module could not be found.

CMake

set(Boost_NO_SYSTEM_PATHS TRUE)
set(BOOST_ROOT "C:/local/boost_1_80_0")
set(CMAKE_SHARED_MODULE_PREFIX "")

find_package(PythonLibs REQUIRED)
include_directories(${PYTHON_INCLUDE_DIRS})
link_directories(${PYTHON_LIBRARIES})

find_package(Boost COMPONENTS python310 REQUIRED)
include_directories(${Boost_INCLUDE_DIRS})
link_directories(${Boost_LIBRARY_DIRS})

add_library(MyLib MODULE MyLib.cpp)

target_link_libraries(MyLib ${Boost_LIBRARIES} ${PYTHON_LIBRARIES})

C++

#include <boost/python.hpp>

    auto* get()
    {
        return "Hello from C++";
    }
    
    BOOST_PYTHON_MODULE(MyLib)
    {
        using namespace boost::python;
        def("get", get);
    }

Python

from MyLib import get
get()

Solution

  • You mention that your binary module is named MyLib.dll. That is the first problem.[1], [2]

    On Windows, CPython expects binary modules to have extension .pyd.

    Either rename the DLL manually, or (as you mention) use PYTHON_ADD_MODULE instead of add_library to achieve the same automatically.

    Once you do this, another problem may appear:

    ImportError: DLL load failed while importing MyLib: The specified module could not be found.
    

    When you're unsure, the best way to debug such errors on Windows is to use a tool like https://github.com/lucasg/Dependencies to find which third party libraries are required, and possibly missing.

    In this case, the likely culprit will be the boost.python DLL. Generally boost.python is linked dynamically, since that allows multiple binary modules that depend on it to work together. Make sure that DLL is in the library search path and things should work.