python - 通过 Ctypes 在 Python 中的 C++ 类
问题描述
我在 C++ 中有这段代码:
#include <iostream>
class Foo{
public:
void bar(){
std::cout << "Hello" << std::endl;
}
};
extern "C" {
Foo* Foo_new(){ return new Foo(); } # I tried __declspec(dllexport) on these funcs, same error
void Foo_bar(Foo* foo){ foo->bar(); }
}
我将它编译成一个 MODULE 库并尝试在 Python 中访问这个类:
import ctypes
lib = ctypes.CDLL('C:\\Users\\avishah\\CLionProjects\\Math\\lib\\libpythonclass.dll')
class Foo(object):
def __init__(self):
self.obj = lib.Foo_new()
def bar(self):
lib.Foo_bar(self.obj)
问题是它无法加载库本身:
Traceback (most recent call last):
File "C:/Users/avishah/PycharmProjects/Math/pythoncpp/test.py", line 4, in <module>
lib = ctypes.CDLL('C:\\Users\\avishah\\CLionProjects\\Math\\lib\\libpythonclass.dll')
File "C:\Python\Python38\lib\ctypes\__init__.py", line 373, in __init__
self._handle = _dlopen(self._name, mode)
FileNotFoundError: Could not find module 'C:\Users\avishah\CLionProjects\Math\lib\libpythonclass.dll' (or one of its dependencies). Try using the full path with constructor syntax.
我在网上尝试了很多示例,但都因此错误而失败...我注意到的一件事是其他示例都有 .so 文件,但由于我在 Windows 上,我使用 .dll 文件,还需要 __declspec( dll 导出)。
编辑: 我正在使用 MinGW 编译器。这与编译器有关吗?我应该使用 MSVC 编译器吗?
解决方案
推荐阅读
- flutter - Flutter 2.0 参数类型“颜色?” 不能分配给参数类型“颜色”
- c# - 是否可以扩展 blazor 组件的属性?
- excel-formula - 如何在 Excel 中对多个 DATEDIF 结果的输出求和
- python - 将linux命令转换为python命令
- optimization - 为什么捆绑第三方库时 Rollup 的 treeshake 不起作用?
- assembly - 将输入与汇编中的字符进行比较时出错
- javascript - Express 提供的是 index.html 而不是我的 Webpack 包。我的配置文件有问题吗?
- django - 通知在 Django 中对我不起作用
- java - Maven构建抛出错误“文件不存在”
- php - Laravel - 我无法将数据输入到我的数据库