Search code examples
pythoncmakepippython-modulepybind11

Use Pybind11 library created with MSYS2,CMake and Make in Python


I have just created a library with Pybind11 from the C++ side: I did it with MSYS2 and CMake and Make. (I have GCC, Make, CMake and Pybind11 installed with the commands)

pacman -S mingw-w64-x86_64-gcc
pacman -S mingw-w64-x86_64-cmake
pacman -S mingw-w64-x86_64-make
pacman -S mingw-w64-x86_64-pybind11

Here example.cpp

#include <pybind11/pybind11.h>

int add(int i, int j) {
    return i + j;
}

PYBIND11_MODULE(example, m) {
    m.doc() = "pybind11 example plugin"; // optional module docstring

    m.def("add", &add, "A function that adds two numbers");
}

Here CMakeLists.txt (in the same directory as example.cpp)

cmake_minimum_required(VERSION 3.3)

# Notre projet est étiqueté hello
project(example)

find_package(Python COMPONENTS Interpreter Development)
find_package(pybind11 CONFIG)

# pybind11 method:
pybind11_add_module(example example.cpp)

Then I ran the commands

mkdir buildmingw
cd buildmingw
cmake .. -G "MinGW Makefiles"
mingw32-make 

and a file example.cp311-win_amd64.pyd is produced.

How can I use this file now in Python?

I already tried putting test.py in the same directory as example.cp311-win_amd64.pyd and then I launched:

python test.py

where test.py looks like this:

import example

print( example.add(7,13 ) )

I get the error message:

D:\Informatik\NachhilfeInfoUni\KadalaSchmittC++\PythonBindC++\buildmingw4>python tes
t.py
Traceback (most recent call last):
  File "D:\Informatik\NachhilfeInfoUni\KadalaSchmittC++\PythonBindC++\buildmingw4\test.py", line 1, in <module>
    import example
ImportError: DLL load failed while importing example: Das angegebene Modul wurde nicht gefunden.

What do I do wrong? How can I correctly import my library?


Solution

  • Judging from its name, your pybind11 extension module is compiled against python 3.11. You probably want to check if the final invocation of python test.py is using a consistent version 3.11 of the python interpreter.

    Alternatively, you can create a venv and invoke all commands (including pip install, cmake, make and python test.py) with the venv activated.