LoginSignup
0
0

More than 1 year has passed since last update.

pybind11で作成したPythonモジュールのインポートでDLL load failed while imorting...と表示された時の対処方法

Last updated at Posted at 2022-07-09

はじめに

少し前にPythonを3.7から3.8に変更しました。環境依存かもしれませんが、mingw64pybind11で作成した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

エラー出力
fail.png

対処方法

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)

結果
succeed.png

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0