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 <math.h>

/*  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<size;i++){
        out_array[i] = cos(in_array[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)
Windows下也可以嘗試Linux下相同的方法,但是可能會報錯,我反正沒有成功,下面使用VS2013生成動態鏈接庫。
1.新建一個Win32 Console Application工程 => 在嚮導中點next => Application type選擇DLL,在Additional options中選擇Empty project
2.向Header Files中加入cos_doubles.h,向Source File中加入cos_doubles.cpp和cos_doubles_wrap.cxx,向工程中加入numpy.i和cos_doubles.i (這是可能會彈出一個對話框,我選的是’否’)工程文件結構
3.project>Properties中點Configuration Manager,設置Configration爲Release,Platform爲×64 => Configuration Properties>VC++ Directories中,在show directories for ‘Include files’中加入Python include 目錄’D:\Anaconda3\include\’ numpy include目錄:’D:\Anaconda3\Lib\site-packages\numpy\core\include’,show dirctories for ‘Library files’中加入Python lib目錄’D:\Anaconda3\libs\’,C/C++>Preprocessor>Preprocessor Definition 加入

WIN32
_DEBUG
_CONSULE
_CRT_SECURE_NO_WARNINGS

屬性配置
右鍵工程,點擊Build,運氣好的話可能一次成功,跳到最後一步,如果報找不到python35_d.lib,則需要修改Python\include 目錄下的 pyconfig.h, object.h 兩個文件

a. 修改 pyconfig.h 
修改 
#ifdef _DEBUG 
# define Py_DEBUG 
#endif #ifdef _DEBUG 
//# define Py_DEBUG 
#endif 

修改 
# ifdef _DEBUG 
# pragma comment(lib,"python24_d.lib") 
# else 
# pragma comment(lib,"python24.lib") 
# endif /* _DEBUG */ # ifdef _DEBUG 
# pragma comment(lib,"python24.lib") 
# else 
# pragma comment(lib,"python24.lib") 
# endif /* _DEBUG */ 

b. 修改object.h 
修改 
#if defined(Py_DEBUG) && !defined(Py_TRACE_REFS) 
#define Py_TRACE_REFS 
#endif #if defined(Py_DEBUG) && !defined(Py_TRACE_REFS) 
// #define Py_TRACE_REFS 
#endif

最後Build Solution,在Release文件夾中會生成cos_doubles.dll,把它改名成_cos_doubles.pyd。把cos_doubles.py, _cos_doubles.pyd和測試文件放到同一個文件夾中,python運行測試。
最終結果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章