Gnuradio中使用到了swig来让python可以调用c++代码。
转自:https://blog.csdn.net/qq_26105397/article/details/83153606
1.安装swig
方法步骤:
a,下载swig源码包
http://www.swig.org/survey.html
b,解压swig安装包,解压并进行安装。
tar -xvf swig-3.0.12.tar.gz
./configure --prefix=/usr/localswig(此处指定安装目录,不指定默认直接默认系统路径)
(如果执行这不成功,缺少prce错误,说明缺少对应的文件,需要安装对应库,个人使用的是乌班图,安装法:apt-get install pcre-dev,或者下载源码包进行安装即可 )
make && make install
至此,swig安装完成。
注:或者直接使用apt-get命令安装swig也可以。
2.使用
1)编写C++代码
test.h
#ifndef __TEST_H #define __TEST_H int add(int a,int b); int sub(int a,int b); #endif
test.cpp
#include "test.h" int add(int a, int b){ return a+ b;} int sub(int a,int b){ return a - b;}
2)编写test.i文件
- %module 后面的名字是被封装的模块名称。封装口,python通过这个名称加载程序
- %{ %}之间所添加的内容,一般包含此文件需要的一些函数声明和头文件。
- %最后一部分,声明了要封装的函数和变量,直接使用%include 文件模块头文件直接包含即可
test.i
// file test.i %module test %{ #define SWIG_WITH_INIT #include "test.h" %} %include "test.h"
3)执行swig命令
swig -python -c++ test.i
此时会生成对应的文件: test_wrap.cxx (即模块名_wrap.cxx)
4)调用python自动化编译工具
利用python提供的自动化编译模块进行编译。编写一个编译文件setup.py。需要的模块是setuptools,没有的话使用pip自行安装。
setup.py
#!/usr/bin/python #-- coding:utf8 -- from setuptools import setup, Extension test_module = Extension("_test", sources = ['test_wrap.cxx', 'test.cpp'],) #其中的名字,与自己编写的文件对应就好,“_test”即模块名称,必须要有下划线 setup(name = 'test',version = '0.1',author = 'SWIG Docs',description = 'Simple swig pht from docs',ext_modules = [test_module],py_modules = ['test'],) #除了与模块名有关的内容,其他的信息可以自己修改
然后执行setup.py:python setup.py build test
5)在python中使用test模块
可在python解释器中或者.py 使用import test,即可使用。