我正在使用 python ctypes 从 python 调用 c++ 中的函数。目前,我有以下 c++ 文件:
五.cpp
extern "C" {
int get_five(){
return 5;
}
}
和Python文件:
五.py
import ctypes
from pathlib import Path
lib = ctypes.CDLL(Path(Path.cwd(),'five.dll').as_posix())
print(lib.get_five())
当我运行它时,它可以工作并打印数字 5。
但是,一旦我在 c++ 文件中包含任何标头,它就会崩溃。所以如果我将文件更改为:
#include <iostream>
extern "C" {
int get_five(){
return 5;
}
}
它坏了,我收到以下错误:
FileNotFoundError:找不到模块“... ive.dll”(或其依赖项之一)。尝试使用带有构造函数语法的完整路径。
我在Windows上编译,使用以下命令:
g++ -shared five.cpp -o five.dll
我可能错过了一些明显的东西,因为我对 C++ 编程非常陌生。不过我好像没找到它是什么。
答案应该是 Mark Tolonen 的:
由于包含 iostream.h,您的 DLL 动态链接到 C++ 运行时 DLL。在 DLL 搜索路径中找不到该 DLL。构建 DLL 时尝试使用
。-static