在Win7环境下,利用SWIG实现Python调用C的方法

时间:2022-09-29 10:32:14

1.系统环境
(1)操作系统为Win7 x64;
(2)VS版本为VS2013_RTM_ULT_CHS,并安装了更新Visual Studio 2013 Update 4 RTM;
(3)Python版本为python-3.4.2 x64;
(4)SWIG版本为swigwin-3.0.5;
(5)编辑软件pycharm-professional-4.0.1。

2.安装SWIG
(1)下载并解压:http://www.swig.org/download.html
(2)将swig.exe所在目录添加到系统变量path中。
【我的配置如下】
D:\Software Packages\Data Analysis\Python\swigwin-3.0.5\;
(3)添加两个系统变量:
PYTHON_INCLUDE : Set this to the directory that contains python.h
PYTHON_LIB : Set this to the python library including path for linking
【我的配置如下】
PYTHON_INCLUDE : C:\Program Files (x86)\Python34\include
PYTHON_LIB: C:\Program Files (x86)\Python34\libs\python34.lib
(4)在命令提示符中运行swig --help,出现Target Language Options等即表明安装成功。

3.用PyCharm新建工程,在其中编写C语言文件palindrome.c

#include <string.h>

//检测是否是回文
int is_palindrome(char *text){
int i, n=strlen(text);
for(i=0; i<=n/2; ++i){
if(text[i] != text[n-i-1])
return 0;
}
return 1;
}

4.在工程中编写接口文件palindrome.i

%module palindrome

%{
#include <string.h>
%}

extern int is_palindrome(char *text);

5.在工程中编写配置文件setup.py
使用python.distutils工具生成扩展模块,并命名为_palindrome(该文件需加下划线,否则会与之后生产的palindrome.py冲突)。

from distutils.core import setup, Extension

setup(name='Palindrome',
version='1.0.0',
description='Simple SWIG example for palindrome test',
ext_modules=[Extension('_palindrome', sources=['palindrome.c', 'palindrome.i'])]
)

6.编译、连接
(1)以管理员身份运行CMD命令处理程序,并将目录切换到工程所在目录。运行

python setup.py build_ext --inplace

可得到一个build文件夹、palindrome.py、palindrome_wrap.c、_palindrome.pyd。
(2)对于error: Unable to find vcvarsall.bat,采用的办法简单粗暴,在“..python安装路径…\Lib\distutils目录下有个msvc9compiler.py找到toolskey = “VS%0.f0COMNTOOLS” % version直接改为 toolskey = “VS你的版本COMNTOOLS”。
因我的VS为2013版,所以【我的配置如下】
路径:C:\Program Files (x86)\Python34\Lib\distutils\msvc9compiler.py
修改:toolskey = “VS120COMNTOOLS”

7.在工程中编写测试文件test.py

import palindrome
print(palindrome.is_palindrome('abc'))
print(palindrome.is_palindrome('abcba'))

运行输出0和1,表明上述该方法成功。

8.参考资料
(1)《Python基础教程(第2版)》
第17.3.1 SWIG章节,第18.3 编译扩展章节
(2)3 Getting started on Windows
http://www.swig.org/Doc1.3/Windows.html
(3)Win7 下Swig安装和配置
http://blog.csdn.net/qingh520/article/details/8955026
(4)swig+python的用法
http://blog.csdn.net/zhanhuai1/article/details/7236262
(5)Windows下python使用SWIG调用C++ dll
http://blog.csdn.net/tobacco5648/article/details/24303299?utm_source=tuicool
(6)[置顶] 彻底解决 error: Unable to find vcvarsall.bat
http://blog.csdn.net/secretx/article/details/17472107