我目前正在学习包装器的工作原理,并在 Windows 10 上使用 SWIG。我用 C++ 编写了一个函数,并尝试在 python 中调用它。在尝试导入 python 模块时出现错误
Traceback (most recent call last):
File "C:\Users\mathw\Documents\projects\hello\hello.py", line 14, in swig_import_helper
return importlib.import_module(mname)
File "C:\Python392\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 666, in _load_unlocked
File "<frozen importlib._bootstrap>", line 565, in module_from_spec
File "<frozen importlib._bootstrap_external>", line 1108, in create_module
File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
ImportError: DLL load failed while importing _hello: The specified module could not be found.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\mathw\Documents\projects\hello\hello.py", line 17, in <module>
_hello = swig_import_helper()
File "C:\Users\mathw\Documents\projects\hello\hello.py", line 16, in swig_import_helper
return importlib.import_module('_hello')
File "C:\Python392\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
ImportError: DLL load failed while importing _hello: The specified module could not be found.
这是它的代码。
hello.cpp
#include <iostream>
#include <vector>
#include <string>
#include "hello.h"
using namespace std;
int foo()
{
vector<string> msg{"Hello", "C++", "World", "from", "VS Code", "and the C++ extension!"};
for (const string &word : msg)
{
cout << word << " ";
}
cout << endl;
return 0;
}
hello.h
int foo();
hello.i
%module hello
%{
extern int foo();
%}
extern int foo();
这些是我在命令提示符中调用的命令。这些命令基于此 video
swig -c++ -python hello.i
g++ -c hello.cpp hello_wrap.cxx -I C:\Python392\include
g++ -shared hello.o hello_wrap.o _hello.pyd -L C:\Python392\libs -l python39
使用这些命令后,我尝试导入 hello 并出现上述错误。