2011-01-07 54 views
23

我在问这个问题,因为我需要构建一个特定的模块(aspell_python,http://wm.ite.pl/proj/aspell-python/)来与我的64位Python 2.6一起工作,它运行在Windows 7(64位当然)机器。我也一直想知道如何用C代码加速某些函数,所以我想在将来为Python创建自己的外部C模块。在Windows上构建64位C Python扩展

任何人都可以请告诉我在C中成功构建64位Python扩展所需的步骤吗?我知道Python,我知道C但我不知道Visual Studio或Windows特定的开发人员事宜。我尝试使用Visual Studio 2008(这是此处可用的唯一商业产品)遵循Python网站上的官方指南(http://docs.python.org/extending/windows.html#building-on-windows),但即使最基本的例子也无法建立。

+5

添加*如何*甚至最基本的例子失败。 – 2011-01-07 10:42:33

+1

例如:在遵循每个方向后,当我尝试构建example_nt时,出现链接器错误,它找不到python26.lib。然后我尝试使用与我的版本的python分发的python26.lib,但这只导致了两个链接器错误:1> example.obj:错误LNK2019:无法解析的外部符号__imp___Py_NoneStruct在函数_ex_foo中引用 1> example.obj:error LNK2019:无法解析的外部符号__imp__Py_InitModule4在函数_medixample – Alexandros 2011-01-07 10:50:49

回答

8

我已经成功地通过之前从在扩展的源代码分发的顶级目录运行下面的命令“Visual Studio 2008中的x64 Win64的命令提示符”编译的C扩展Python的64位Windows:

set DISTUTILS_USE_SDK=1 
set MSSdk=1 
python setup.py install 
2

我会使用Shed Skin:只需下载,解压缩,运行init bat和compile your Python code

如果这样不起作用,并且您可以使用Microsoft的C编译器环境,请尝试CythonThis tutorial将正常的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)