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.o和coding_wrap.o
然后鏈接得到動態庫
g++ -lssl -shared coding.o coding_wrap.o libcode.a -o _coding.so
注意這邊鏈接的時候使用了-lssl選項是因為加解密的靜態庫的實現中使用openssl
然后得到了_coding.so這個動態庫
至此,我們所需要的兩個文件_coding.so和coding.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