SWIG ---- Python调用C++
SWIG ---- Python 调用C++
使用 SWIG(Simplified Wrapper and Interface Generator) 实现在Python中调用C++的代码.
C++ Source Code
// service.h
class Service
{
public:
Service();
int add(int a, int b);
};
// service.cpp
#include "service.h"
Service::Service()
{
}
int add(int a, int b)
{
return a + b;
}
SWIG interface code
// service.i
%module service;
%{
#include "service.h"
%}
%include "service.h"
Steps
1 使用SWIG生成service.py 和 service_wrap.cxx
In order to compile the C/C++ wrappers, the compiler needs the Python.h header file.
swig -c++ -python service
2 编译C++源码生成 service.o
On some platforms, you could also need to generate position-independent code (PIC), by using a compiler option such as -fPIC. Notably, the x86_64 (Opteron and EM64T) platform requires it, and when using the GNU Compiler Suite, you will need to modify the previous example as follows:
g++ -c -fPIC service.h service.cpp
3 编译service_wrap.cxx生成service_wrap.o
g++ -c -fPIC service_wrap.cxx -I/usr/local/include/python2.7
4 链接service.o与service_wrap.o生成动态库_servic.so
g++ -shared service.o service_wrap.o -o _service.so
测试
// test.py
import service
ser = service.Service()
print ser.add(1,2)
python test.py
参考资料
链接: SWIG and Python