python通过swig调用静态库

swig - Simplified Wrapper and Interface Generator

swig可以支持python,go,php,lua,ruby,c#等多种语言的包裹

本文主要记录如何使用swig创建一个可供python中调用静态库接口

首先手上有一个头文件(.h)以及一个静态库文件(.a),这是常见的api分发方式

libcode.a code.h

看一下code.h中的内容:

int encode(const char* salt, int version, const char* from, string& to);

int decode(const char* salt, int version, const char* from, string& to);

可以知道包含了一个加密和一个解密的函数,我们这里只是用解密来举例

为了使用swig进行包裹,我们先创建一个自己的头文件和实现文件coding.cpp coding.h

看一下内容:

coding.cpp

#include "code.h"

using std::string;
const int version = 1;

string decode(int version, string salt, string from)
{
    string to;
    int ret = decode(salt.c_str(), version, from.c_str(), to);
    if(ret != 0)
    {
        return "";
    }
    return to;
}

coding.h

#include <string>

std::string decode(int version, std::string salt, std::string from);

接下来我们定义我们的swig入口文件coding.i

%module coding
%include "std_string.i"

%{
#define SWIG_FILE_WITH_INIT
#include "coding.h"
%}

std::string decode(int version, std::string salt, std::string from);

注意这里由于使用了std::string,所以必须%include "std_string.i"

然后,我们使用swig来获取到包裹文件

swig -c++ -python coding.i

执行后会得到coding_wrap.cxx文件以及coding.py文件

接下来我们编译出几个目标文件:

g++ -O2 -fPIC -c coding.cpp
g++ -O2 -fPIC -c coding_wrap.cxx -I/usr/include/python2.7

得到coding.ocoding_wrap.o

然后链接得到动态库

g++ -lssl -shared coding.o coding_wrap.o libcode.a -o _coding.so

注意这边链接的时候使用了-lssl选项是因为加解密的静态库的实现中使用openssl

然后得到了_coding.so这个动态库

至此,我们所需要的两个文件_coding.socoding.py就都已经拿到了,下面的python代码演示了如何使用

import coding
coding.decode(1, "xxxxx-salt-xxxxx", "xxxxxxxxxx-encoded-text-xxxxxxxxxxxx")

参考:
http://www.swig.org/Doc1.3/Python.html#Python_nn22
http://www.swig.org/Doc1.3/Library.html#Library_nn14
http://www.deep-nlp.com/?p=31

posted on 2019-03-19 21:44  caiminfeng  阅读(2591)  评论(2编辑  收藏  举报

导航