# Python调用C++函数（SWIG，VS2013使用numpy.i完成Numpy与C++数组转换）

1.安装SWIG
windows：官网下载，解压到D盘，将swig.exe所在文件夹添加到系统路径，如：D:\swigwin-3.0.12\
Linux：sudo apt-get install swig
2.下载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]);
}
}

/*  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);
}
%}

4.使用SWIG编译生成.py和.cxx

swig -c++ -python cos_doubles.i

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

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
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

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

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120