python - 无法使用 python ctypes 加载 C++ 共享库
问题描述
解决方案
我自己找到解决方案。解决方案是:
- 使用MinGW编译器或 Microsoft C/C++ 编译器。
- 使用 Python 32 位解释器。
- 无需从编译器 bin 文件夹中复制 dll。
首先,我之前使用TDM-GCC MinGW Compiler作为 C/C++ 编译器。然后我尝试另一个编译器:MinGW。我不能告诉你他们之间有什么不同,我不是专业人士。但是当我使用ctypes
在解释器中加载由两者编译的两个不同的 dll 库时,它们会产生不同的错误消息Python 3.6.6 64 bit
。他们都失败了Python 3.6.6 64 bit
翻译。
我尝试使用 32 位 python 来加载 dll 库。加载库成功。
pylib.cpp代码:
#include <iostream>
using namespace std;
class Foo {
public:
void bar() {
cout << "Hello" << endl;
}
};
extern "C" {
Foo* Foo_new() { return new Foo(); }
void Foo_bar(Foo* foo) { foo->bar(); }
}
编译命令:
g++ -shared -o pylib.dll pylib.cpp
pylib.py代码:
from ctypes import *
lib = cdll.LoadLibrary('pylib.dll')
f = lib.Foo_new()
lib.Foo_bar(f)
输出:
Hello
感谢 pschill 和其他人提出新方法。
推荐阅读
- visual-studio-code - Python 扩展没有提示选择 venv
- c++ - 递归深度优先搜索功能不起作用
- javascript - useLocation 不渲染道具 - Gatsby 路由
- sql - 在 SQL 表的所有列中搜索值
- ibm-mq - 如何编写 Mq 命令显示 curdepth 大于 80% of maxdepth?
- javascript - Typedefs 在 Vscode 中无法正常工作
- java - 覆盖方法会导致 AndroidStudio 中出现冗余、重复的注解
- postgresql - postgresql 最大连接数是什么意思?
- c# - 如何在 XML 序列化中仅排除子类的名称,而不是字段?
- reactjs - 如何在 React 中编辑材质 ui 的卡片样式