Python调用C++函数(SWIG,VS2013使用numpy.i完成Numpy与C++数组转换)

最近尝试使用Python调用C++函数,发现网上都是一些简单的例子,涉及到Python Numpy数组与C++数组转换的例子比较少,所以花费了一些时间,搞懂了SWIG使用numpy.i接口文件完成Numpy与C++数组转换。相比于其它几种方式,使用SWIG接口文件编写比较简单,编译也很方便,主要是不太好调试,因为是编译成.dll或者.so才能在Python中调用。 
1.安装SWIG 
windows:官网下载,解压到D盘,将swig.exe所在文件夹添加到系统路径,如:D:\swigwin-3.0.12\ 
Linux:sudo apt-get install swig 
2.下载numpy.i文件  
有些在numpy安装目录下直接就有,没有的话可以到GitHub下载numpy.i地址、numpy.i说明文档,numpy/tools/swig/numpy.i 
3.编写自己的函数接口文件

//cos_doubles.h
void cos_doubles(double*in_array,double*out_array,intsize);

//cos_doubles.cpp
#include 

/*  Compute the cosine of each element in in_array, storing the result in
 *  out_array. */
void cos_doubles(double * in_array, double * out_array, int size){
    int i;
    for(i=0;i

根据numpy.i说明文档撰写cos_doubles.i文件:

/*  Example of wrapping a C function that takes a C double array as input using
 *  numpy typemaps for SWIG. */

%module cos_doubles
%{
    /* the resulting C file should be built as a python extension */
    #define SWIG_FILE_WITH_INIT
    /*  Includes the header in the wrapper code */
    #include "cos_doubles.h"
%}

/*  include the numpy typemaps */
%include "numpy.i"
/*  need this for correct module initialization */
%init %{
    import_array();
%}

/*  typemaps for the two arrays, the second will be modified in-place */
%apply (double* IN_ARRAY1, int DIM1) {(double * a, int size_a)}
%apply (double* INPLACE_ARRAY1, int DIM1) {(double *b, int size_b)}

/*  Wrapper for cos_doubles that massages the types */
%inline %{
    /*  takes as input two numpy arrays */
    void cos_doubles_func(double * a, int size_a, double* b, int size_b) {
        /*  calls the original funcion, providing only the size of the first */
        cos_doubles(a, b, size_a);
    }
%}

如果是固定大小的数组,也可以使用%apply (double IN_ARRAY1[ANY]) {(double a[63])}方式 
4.使用SWIG编译生成.py和.cxx
将numpy.i、cos_doubles.h、cos_doubles.cpp、cos_doubles.i放在同一文件夹下,命令行输入(Linux与windows相同,C语言去掉-c++):

swig -c++ -python cos_doubles.i

此时文件夹下会生成cos_doubles.py与cos_doubles_wrap.cxx文件 
5.1.编译生成动态链接库文件(Linux) 
Linux:新建setup.py文件

from distutils.core import setup, Extension
import numpy


cos_doubles_module = Extension('_cos_doubles',
                           sources=['cos_doubles_wrap.cxx', 'cos_doubles.cpp'], )

setup (name = 'cos_doubles',
       version = '0.1',
       author      = "SWIG Docs",
       description = """Simple swig example from docs""",
       ext_modules = [cos_doubles_module],
       include_dirs = [numpy.get_include()],
       py_modules = ["cos_doubles"], )

命令行输入:

python setup.py build_ext --inplace

此时文件夹下会生成_cos_doubles.so文件,新建runme.py演示程序,测试能否调用:

import numpy as np
import matplotlib.pyplot as plt
import cos_doubles

x = np.arange(0, 2 * np.pi, 0.1)
y = np.empty_like(x)

cos_doubles.cos_doubles_func(x, y)
plt.plot(x, y)
plt.show()

5.2.编译生成动态链接库文件(Windows) 


IF(WIN32)
	INCLUDE_DIRECTORIES(D:\\Anaconda3\\include D:\\Anaconda3\\Lib\\site-packages\\numpy\\core\\include)
	LINK_DIRECTORIES(D:\\Anaconda3\\libs)
	SET (EXTRA_LIBS ${EXTRA_LIBS}
	)
ELSE()
ENDIF()

add_library( # Sets the name of the library.
		cos_doubles

        # Sets the library as a shared library.
        SHARED

        # Provides a relative path to your source file(s).
		cos_doubles.cpp
		cos_doubles_wrap.cxx
        )
TARGET_LINK_LIBRARIES(cos_doubles ${EXTRA_LIBS})

最后Build Solution,在Release文件夹中会生成cos_doubles.dll,把它改名成_cos_doubles.pyd。把cos_doubles.py, _cos_doubles.pyd和测试文件放到同一个文件夹中,python运行测试。 

你可能感兴趣的:(C/C++)