首页 > 解决方案 > 通过 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 编译器吗?

标签: pythonc++ctypes

解决方案


推荐阅读