在Windows上构建64位C Python扩展
我问这个问题是因为我需要构建一个特定的模块(aspell_python,http://wm.ite.pl/proj/aspell-python/),让它能在我的64位Windows 7系统上的Python 2.6中运行。我一直想知道如何用C语言加速某些功能,所以我希望将来能为Python制作自己的外部C模块。
有没有人能告诉我,成功构建一个64位的Python C扩展需要哪些步骤?我会Python,也会C,但对Visual Studio或者Windows特定的开发事情不太了解。我试着按照Python官网上的官方指南(http://docs.python.org/extending/windows.html#building-on-windows)用Visual Studio 2008来操作(这是我这边唯一能用的商业产品),但即使是最基本的例子也无法成功构建。
2 个回答
2
我建议你使用Shed Skin:只需下载,解压,运行初始化的批处理文件,然后编译你的Python代码。
如果这样不行,而且你能让微软的C编译器环境正常工作,可以试试Cython。这个教程对比了普通的Python扩展和它生成的C版本。以下是更新的摘录:
c_prime.pyx:
def calculate(long limit):
cdef long current
cdef long divisor
primes = []
divisor = 0
for current in range(limit):
previous = []
for divisor in range(2, current):
if current % divisor == 0:
break
if divisor == current - 1:
primes.append(current)
return primes
setup.py:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
setup(
name = 'PrimeTest',
ext_modules=[
Extension('c_prime', ['c_prime.pyx'])
],
cmdclass = {'build_ext': build_ext}
)
编译:
python setup.py build_ext --inplace --compiler=msvc
test_prime.py:
from timeit import Timer
t = Timer('c_prime.calculate(10000)', 'import c_prime')
reps = 5
print(sum(t.repeat(repeat=reps, number=1)) / reps)
9
我之前在64位的Windows上成功编译过Python的C扩展。这个过程是通过在扩展源代码的顶层目录下,使用“Visual Studio 2008 x64 Win64命令提示符”运行以下命令来完成的:
set DISTUTILS_USE_SDK=1
set MSSdk=1
python setup.py install