はじめに
少し前にPythonを3.7から3.8に変更しました。環境依存かもしれませんが、mingw64とpybind11で作成したPythonモジュールをインポートしようすると、"DLL load failed while importing ..."となり、インポートができなくなりました。githubのissuesに対処方法が書かれていたので、そのメモです。
環境
- Windows 10 home
- Python(3.8.10)
- pybind11(2.4)
- mingw64(gcc6.3)
うまくいかない状況
うまくいかない状況を記載しておきます。
以下のサンプルコードをmingw64とpybind11でythonモジュールを作成しました。インポートしようとするとDLL load failed...とでて、モジュールのインポートができませんでした。
#include <pybind11/pybind11.h>
int add(int i, int j){
return i+j;
}
PYBIND11_MODULE(example, m){
m.doc() = "pybind11 example plugin";
m.def("add", &add, "A function that adds two numbers");
}
pybind11を置いているincludeパス、Pythonのincludeパス・libsパスを指定して、コンパイルします。
g++ -shared -std=c++14 example.cpp -o example.pyd -I"D:\include" -I"C:\Users\username\AppData\Local\Programs\Python\Python38\include" -L"C:\Users\username\AppData\Local\Programs\Python\Python38\libs" -lpython38
作成モジュールのインポートするとエラーが出力されます。
import example
対処方法
githubのissuesによるとmingw64\binのパスがうまく読めていないようです。os.add_dll_directory
を使ってmingw64\binを指定します。
import os
os.add_dll_directory("C:\\mingw64\\bin")# MinGWをフォルダのbinを指定
import example
example.add(10,8)