使用swig在python中调用C++

1、安装swig

下载链接: http://www.swig.org/survey.html

tar   -xvf   swig-3.0.12.tar.gz
./configure  --prefix=/usr/localswig(此处指定安装目录,不指定默认直接默认系统路径)
make && make install

注意:如果在第二步中不成功,可能是没有安装pcre库,安装pcre步骤如下:

pcre下载链接:http://www.pcre.org/

tar -xzvf pcre-8.21.tar.gz
cd pcre-8.21
./configure  && make && make install

之后,再来测试swig是否安装成功,使用下面语句:

swig -version

可能会报“找不到libpcre.so.1的错误”,解决办法如下,建立软连接:

sudo ln -s /pcre-8.21/.libs/libpcre.so.0.0.1 /usr/lib/libpcre.so.1

2、建立接口

以一个简单的小程序为例:

(1)编辑头文件和源文件

//mytest.h
int add(int a,int b);

int  sub(int a,int b);
 //test.cpp
int add(int a, int b){   return a+ b;}   
int sub(int a,int b){ return a - b;}

(2)编辑对应的.i文件

//%module 后面的名字是被封装的模块名称。封装口,python通过这个名称加载程序
//%{  %}之间所添加的内容,一般包含此文件需要的一些函数声明和头文件。

//最后一部分,声明了要封装的函数和变量,直接使用%include 文件模块头文件直接包含即可

   //file mytest.i

    %module  mytest

    %{

      #define SWIG_WITH_INIT

      #include "mytest.h"

   %}

   %include "mytest.h  "

(3)执行命令编辑.i文件

swig    -python    -c++    mytest.i

执行完成之后会生成对应的文件: 模块名_warp.cxx(这里就是mytest_warp.cxx)

(4)编写setup.py文件

from distutils.core import setup
from distutils.extension import Extension

test_module = Extension('_mytest', sources=['mytest_wrap.cxx', 'mytest.cpp'],)

setup(name = 'mytest',
    version = '0.1',
    author = 'SWIG Docs',
    description = 'Simple swig pht from docs',
    ext_modules = [test_module],
    py_modules = ['mytest']

执行该setup.py文件

python setup.py build

执行完之后会在同级目录的build文件夹的lib文件夹下生成对应的.so文件和mytest.py文件;

之后要注意:要在这个目录下编写调用这个C++模块的py脚本!!!因为执行完setup.py之后在setup.py的同级目录下也会生成一个mytest.py文件,但没有对应的.so文件,直接在这个里面编写py脚本进行调用的话会由于没有动态链接库而报错!!!

(5)编写python脚本调用C++

import mytest

a = mytest.add(1, 2)
print(a)

b = mytest.sub(2, 1)
print(b)

猜你喜欢

转载自www.cnblogs.com/zf-blog/p/11899556.html