【问题标题】:Building 64-bit C Python extensions on Windows在 Windows 上构建 64 位 C Python 扩展
【发布时间】:2011-01-07 10:20:42
【问题描述】:

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

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

【问题讨论】:

  • 添加如何即使是最基本的例子也失败了。
  • 例如:遵循每个方向后,当我尝试构建 example_nt 时,我收到链接器错误,它找不到 python26.lib。然后我尝试使用与我的python版本一起分发的python26.lib,但这只导致两个链接器错误:1>example.obj:错误LNK2019:未解析的外部符号__imp___Py_NoneStruct在函数_ex_foo中引用 1>example.obj:错误LNK2019 : 函数 _initexample 中引用的未解析的外部符号 __imp__Py_InitModule4
  • 之后,我尝试自己构建python26.lib,方法是使用VS2008从源代码构建整个python 2.6项目,这当然会导致许多错误。然而,它产生了一个 python26_d.lib,当与 example_nt 一起编译时仍然给出链接器错误
  • 如果您安装了带有 64 位编译器的 Visual Studio 2008 Professional,则使用“python setup.py build”构建 example_nt 应该可以在 Python 2.6.6 AMD64 上开箱即用。
  • 很可能您没有正确安装 Visual Studio 2008 Professional。 64 位编译器是一个需要在安装时启用的选项。如果您使用的是 Visual Studio 2008 Express,则它不附带 64 位编译器。

标签: python c 64-bit


【解决方案1】:

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

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

【讨论】:

  • 这似乎适用于 VS 2012 对我来说......我已经很痛苦了。
【解决方案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)

【讨论】:

    猜你喜欢
    • 2019-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-04
    • 2011-12-21
    • 1970-01-01
    相关资源
    最近更新 更多