首页 > 解决方案 > 无法使用 python ctypes 加载 C++ 共享库

问题描述

标签: pythonc++

解决方案


我自己找到解决方案。解决方案是:

  1. 使用MinGW编译器或 Microsoft C/C++ 编译器。
  2. 使用 Python 32 位解释器。
  3. 无需从编译器 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 和其他人提出新方法。


推荐阅读