最近嘗試使用Python調(diào)用C++函數(shù)拴还,發(fā)現(xiàn)網(wǎng)上都是一些簡(jiǎn)單的例子,涉及到Python Numpy數(shù)組與C++數(shù)組轉(zhuǎn)換的例子比較少欧聘,所以花費(fèi)了一些時(shí)間片林,搞懂了SWIG使用numpy.i接口文件完成Numpy與C++數(shù)組轉(zhuǎn)換。相比于其它幾種方式,使用SWIG接口文件編寫(xiě)比較簡(jiǎn)單费封,編譯也很方便焕妙,主要是不太好調(diào)試,因?yàn)槭蔷幾g成.dll或者.so才能在Python中調(diào)用弓摘。
1.安裝SWIG
windows:官網(wǎng)下載焚鹊,解壓到D盤,將swig.exe所在文件夾添加到系統(tǒng)路徑韧献,如:D:\swigwin-3.0.12
Linux:sudo apt-get install swig
2.下載numpy.i文件
有些在numpy安裝目錄下直接就有末患,沒(méi)有的話可以到GitHub下載numpy.i地址、numpy.i說(shuō)明文檔势决,numpy/tools/swig/numpy.i
3.編寫(xiě)自己的函數(shù)接口文件
//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]);
}
}
根據(jù)numpy.i說(shuō)明文檔撰寫(xiě)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);
}
%}
如果是固定大小的數(shù)組阻塑,也可以使用%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語(yǔ)言去掉-c++):
swig -c++ -python cos_doubles.i
此時(shí)文件夾下會(huì)生成cos_doubles.py與cos_doubles_wrap.cxx文件
5.1.編譯生成動(dòng)態(tài)鏈接庫(kù)文件(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
此時(shí)文件夾下會(huì)生成_cos_doubles.so文件走搁,新建runme.py演示程序,測(cè)試能否調(diào)用:
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.編譯生成動(dòng)態(tài)鏈接庫(kù)文件(Windows)
Windows下也可以嘗試Linux下相同的方法迈窟,但是可能會(huì)報(bào)錯(cuò)私植,我反正沒(méi)有成功,下面使用VS2013生成動(dòng)態(tài)鏈接庫(kù)车酣。
1.新建一個(gè)Win32 Console Application工程 => 在向?qū)е悬c(diǎn)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 (這是可能會(huì)彈出一個(gè)對(duì)話框曲稼,我選的是'否')
WIN32
_DEBUG
_CONSULE
_CRT_SECURE_NO_WARNINGS
右鍵工程娘摔,點(diǎn)擊Build窄坦,運(yùn)氣好的話可能一次成功,跳到最后一步凳寺,如果報(bào)找不到python35_d.lib鸭津,則需要修改Python\include 目錄下的 pyconfig.h, object.h 兩個(gè)文件
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文件夾中會(huì)生成cos_doubles.dll,把它改名成_cos_doubles.pyd肠缨。把cos_doubles.py, _cos_doubles.pyd和測(cè)試文件放到同一個(gè)文件夾中,python運(yùn)行測(cè)試逆趋。