swig-python对C++的接口

前言:

swig可以实现多种高级语言(如python,R,Java等)对C/C++的使用,提供一种转换的接口.这里由于项目的需要,介绍下Python对C++的支持.(本文部分参考其它网络文章,但代码均经过验证可行)


安装SWIG(ubuntu 14.04):

  • 1.安装pcre(pcre提供对正则表达式的支持)

sudo apt-get update
sudo apt-get install libpcre3 libpcre3-dev
可能还需要安装:
sudo apt-get install openssl libssl-dev

  • 2.安装SWIG:

sudo apt-get install swig

安装结束


简单使用

  • 1.用c++语言编写头文件和源文件为:
    头文件example.h:
    int fact(int n);

源文件example.cpp:

   #include "example.h"

   int fact(int n){
    if(n<0){
    return 0;
    }
    if(n==0){
    return 1;
    }
    else{
    return (1+n)*fact(n-1);
    }
   }
  • 2.写swig模块写一个文件example.i:
%module example

%{
#define SWIG_FILE_WITH_INIT
#include "example.h"
%}

int fact(int n);
  • 3.使用swig生产cxx文件,建python模块:

swig -c++ -python example.i

执行完命令后会生成两个不同的文件:example_wrap.cxx和example.py.

  • 4.最后一步,利用python自带工具distutils生成动态库:
    python自带一个distutils工具,可以用它来创建python的扩展模块.
    要使用它,必须先定义一个配置文件,通常是命名为setup.py
"""
setup.py
"""

from distutils.core import setup, Extension

example_module = Extension('_example',
            sources=['example_wrap.cxx','example.cpp'],
            )

setup (name='example',
       version='0.1',
       author="SWIG Docs",
       description="""Simple swig example from docs""",
       ext_modules=[example_module],
       py_modules=["example"],
      )

注意:头文件和源文件都是example.*,那么setup.py脚本中Extension的参数必须为"_example"

  • 5.编译

python setup.py build_ext --inplace

  • 6.测试
    python命令行:
>>>import example
>>>example.fact(4)
24
>>>

*7.支持STL

*7.1. vector

%module example

%{
#define SWIG_FILE_WITH_INIT
#include "example.h"
%}
%include stl.i
namespace std{
%template(VectorOfString) vector;
}

int fact(int n);
std::vector getname(int n);

*7.2. vector >

%module example

%{
#define SWIG_FILE_WITH_INIT
#include "example.h"
%}
%include stl.i
namespace std{
%template(stringvector) vector;
%template(stringmat) vector >;
}

int fact(int n);
std::vector > getname(int n);

*7.3. vector >二维vector(多维vector定义+struct)

%module example
%{
#define SWIG_FILE_WITH_INIT
#include "example.h"
%}

%include stl.i
struct point
{
int i;
int j;
};

namespace std{
%template(stringvector) std::vector;
%template(stringmat) std::vector >;
}
std::vector > getname(int n); 
/*结束
namespace std块中,第一个vector是第二个vector的基础,也就是第一个是第二个的子集,需要先申明内部,然后才能定义更加复杂的部分,比如我之前只定义了如下的namespace std形式:
namespace std{
%template(stringvector) std::vector;
%template(stringmat) std::vector >;
}
寻找了好长时间也没找到错误的原因,后来查阅外文资料,才知道这个必须要逐个声明,也就是这里,它不知道std::vector是怎么来的,所以我必须要先声明std::vector才行,即上文形式,这个问题困扰了我好长时间,现在终于解决了.
*/

你可能感兴趣的:(swig-python对C++的接口)