一、 准备扩展模块源码
准备好需要扩展的c/c++程序,如:
/* service.h */
#ifndef SERVICE_H
#define SERVICE_H
class Service
{
public:
Service();
~Service();
int add(int a, int b);
};
#endif
/* service.cpp */
#include "service.h"
Service::Service()
{
}
Service::~Service()
{
}
int Service::add(int a, int b)
{
return a + b;
}
二、 编写swig接口脚本
编写
service.i
SWIG接口
/* service.i */
%module Service
%{
#define SWIG_FILE_WITH_INIT
#include "service.h"
%}
%include "service.h"
三、 通过swig封装接口
执行
swig -c++ -python service.i
指令,生成service_wrap.cxx
和service.py
文件
四、 编写安装脚本
编写
setup.py
安装脚本
from distutils.core import setup, Extension
pht_module = Extension('_Service',
sources=['service_wrap.cxx',
'service.cpp'
],
)
setup(name = 'Service',
version = '0.1',
author = 'SWIG Docs',
description = 'Simple swig pht from docs',
ext_modules = [pht_module],
py_modules = ['Service'],
)
五、 生成扩展模块(.so)
执行
python setup.py build_ext --inplace
指令,生成build
文件夹 和_service.cpython-35m-x86_64-linux-gnu.so
动态库
六、 编写测试程序
编写
test.py
测试程序,测试c++扩展模块功能
import Service
x = 1
y = 2
service = Service.Service()
z = service.add(a = x, b = y)
print(z)
七、 查看测试结果
执行
python test.py
指令,查看测试结果