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
- 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.deep-nlp.com/?p=31
来源: http://www.bubuko.com/infodetail-2993125.html