在Windows上构建64位C Python扩展

2024-06-18 11:57:56 发布

您现在位置:Python中文网/ 问答频道 /正文

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

有谁能告诉我在C中成功构建64位Python扩展所需的步骤吗?我知道Python,我知道C,但我不知道Visual Studio或Windows特定的开发人员问题。我试图使用Visual Studio 2008(这是这里唯一可用的商业产品)来遵循Python网站上的官方指南(http://docs.Python.org/extensing/windows.html#building on windows),但即使是最基本的示例也无法构建。


Tags: 模块函数代码机器httpwindows步骤proj
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

设置.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}
)

编译:

^{}

测试时间:

from timeit import Timer

t = Timer('c_prime.calculate(10000)', 'import c_prime')
reps = 5
print(sum(t.repeat(repeat=reps, number=1)) / reps)

我以前在64位Windows上成功编译过Python的C扩展,方法是从扩展源发行版的顶级目录中的“Visual Studio 2008 x64 Win64命令提示符”运行以下命令:

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

相关问题 更多 >