python - 在 Python 中加载 C++ 类

标签 python c++ dll

我正在尝试在 Python 中导入 C++ 类。 我知道我可以使用 BoostPython、SWIG 或 Cython,但只是出于教学目的,我正在尝试使用 extern "C" 手动导出 C++ 方法和函数。简而言之,我正在尝试复制 this .

我的环境是 Windows 10,Anaconda 3 和 Python 3.6。我已经安装了 mingw64 4.8.3 作为 C/C++ 编译器。

这是我的foo.cpp:

#include <iostream>
// A simple class with a constuctor and some methods...
class Foo
{
    public:
        Foo(int);
        void bar();
        int foobar(int);
    private:
        int val;
};
Foo::Foo(int n)
{
    val = n;
}
void Foo::bar()
{
    std::cout << "Value is " << val << std::endl;
}
int Foo::foobar(int n)
{
    return val + n;
}
// Define C functions for the C++ class - as ctypes can only talk to C...
extern "C"
{
    Foo* Foo_new(int n) {return new Foo(n);}
    void Foo_bar(Foo* foo) {foo->bar();}
    int Foo_foobar(Foo* foo, int n) {return foo->foobar(n);}
}

我是这样编译的:g++ -c -fPIC foo.cpp -o foo.o。 输出是:

foo.cpp:1:0: warning: -fPIC ignored for target (all code is position independent) [enabled by default]
#include <iostream>
^

然后,我以这种方式编译:g++ -shared -Wl,-soname,libfoo.dll -o libfoo.dll foo.o 没有错误/警告。文件 libfoo.dll 已出现在文件夹中。

当我在 Python 中尝试时:

import ctypes
lib = ctypes.windll.LoadLibrary('libfoo.dll')

我收到错误 OSError: [WinError 126] 找不到指定的模块。我的 Python 工作目录是 libfoo.dll 文件夹。

我试图创建一个简单的 C-HelloWorld 库:我以相同的方式编译(gcc 的一部分而不是 g++),我成功地将它加载到 Python 中.

问题出在哪里?它在编译说明中吗?还是在代码中?

最佳答案

我找到了一个从@Scheff 评论开始的解决方案。

在 Linux 上(我在 Ubuntu 16、GCC 4.4.0 和 Python 3.6 上试过),我的问题代码在没有修改的情况下运行良好(在代码和编译指令上)。

在 Windows 上,我以这种方式修改了 extern "C" block :

extern "C"
{
     __declspec(dllexport) Foo* Foo_new(int n) {return new Foo(n);}
     __declspec(dllexport) void Foo_bar(Foo* foo) {foo->bar();}
     __declspec(dllexport) int Foo_foobar(Foo* foo, int n) {return foo->foobar(n);}
}

然后我像以前一样重新编译。

此后,我能够按照 question link 中的描述导入模块和 C++ 类.

要实现 C++ 打印功能,请参阅 this question .

关于python - 在 Python 中加载 C++ 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52568315/

相关文章:

c++ - 可以从 C++ DLL 项目创建 DYLIB 吗?

c# - 使用不同版本的引用 DLL

python - 如何获取 Azure 表查询中返回的实体数量?

c++ - 要包含在 Visual Studio C++ 中以使用 CUDA 的文件/目录?

c++ - 将数据从 stringstream 存储到 unsigned long 中的可能方法是什么?

windows - 重定向插件 DLL list 中的依赖 DLL

带有用于 RESTful API 的社交网络的 Python OAuth2 服务器

python - 快速将原始文件转换为带水印的 pdf 到 swf

python - unittest 无法发现/运行测试

android - 使用 native 代码进入会导致 Android Studio 中出现垃圾