首页 > 编程语言 > 详细

python通过swig调用静态库

时间:2019-03-19 22:10:28      阅读:191      评论:0      收藏:0      [点我收藏+]
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

python通过swig调用静态库

原文:https://www.cnblogs.com/caiminfeng/p/10554802.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!