使用 SWIG 的 C++ 的 Python 包装器

标签 python c++ gcc static-libraries swig

我将使用 SWIG 为一些 C++ 代码编写一个 Python 包装器。主类是Cryptographer,它使用两个静态库,它们是 libgmp.a libgmpxx.a 。所以我的代码是这样的(为了简单起见,删除了一些实现代码):

示例.h:

/* example.h */
#include <string.h>
#include <string>
#include <stdlib.h>
#include <vector>
#include <sstream>
#include "gmp.h"
#include "gmpxx.h"

using namespace std;

class Cryptographer {
    private:
        mpz_class num;
    public:
        Cryptographer();
        virtual ~Cryptographer();
};

示例.cpp:

/* example.cpp */
#include "example.h"

Cryptographer::Cryptographer() {
    num = 12;
}

Cryptographer::~Cryptographer() {
}

对于上面的两个文件,创建了一个 SWIG 接口(interface):

示例.i:

%module example
%{ 
    #define SWIG_FILE_WITH_INIT
    #include "example.h"
%}
%include "example.h"

然后我运行这些命令:(取自 here )

swig -c++ -python example.i // creates "example_wrap.cxx"

gcc -c -fPIC example_wrap.cxx -I/usr/include/python2.7 // outputs "example_wrap.o"

gcc -c -fPIC example.cpp -I/usr/include/python2.7 // creates "example.o"

g++ -shared example_wrap.o example.o -o example.so // creates "example.so"

然后我尝试在 python2.7 中导入 example 模块,但不幸的是它不起作用:

Python 2.7.12 (default, Nov 19 2016, 06:48:10)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import example
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
ImportError: ./example.so: undefined symbol: __gmpz_set_si

我猜那些 libgmplibgmpxx 库有问题,在链接过程中没有正确链接,但我不知道如何修复它。

顺便说一句,所有需要的文件都可以通过 this link 访问.

最佳答案

这在 gcc 6.3.0 中工作正常:

g++ -shared -o _example.so example_wrap.o example.o libgmp.a libgmpxx.a

不过,您可能需要提供 .a 文件的完整路径。

这些库需要位置无关的代码(又名 -fPIC)编译。

重建库: 1)下载这个:https://gmplib.org/download/gmp/gmp-6.1.2.tar.bz2 2) 将文件解压到所选目录中。 3) 从该目录运行以下命令:

./configure --with-pic=yes --enable-cxx

如果一切顺利,您将拥有一个Makefile。 因此,请立即调用 makemake install。完毕。

关于使用 SWIG 的 C++ 的 Python 包装器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47377338/

相关文章:

python - 重复平铺背景pygame

python - yowsup - 集成发送和接收

c++ - 如果没有目标函数,如何检查约束是否可行?

gcc - 搜索最近的 GCC GIMPLE 语法

c - 为什么 char name[1] 可以容纳 1 个以上的字符?

c - 在不更改代码的情况下使用 gcc 的功能多版本控制是否可行?

python - numpy in1d 返回不正确的结果?

python - 列表项与字典比较的单行解决方案

c++ - 将元素从一个数组复制到另一个 C++

c++ - 将 vector 的一部分传递给 C++ 中的函数