Building 64-bit C Python extensions on Windows

2019-01-21 16:55发布

问题:

I am asking this question because I need to build a specific module (aspell_python, http://wm.ite.pl/proj/aspell-python/) to work with my 64-bit Python 2.6 which runs on a Windows 7 (64-bit of course) machine. I also always wanted to know how to speed up certain functions with C code so I'd like to make my own external C modules for Python in the future.

Can anyone please tell me the steps required to successfully build a 64-bit Python extension in C? I know Python, I know C but I don't know about Visual Studio or Windows specific developer matters. I tried to follow the official guide on the Python web site (http://docs.python.org/extending/windows.html#building-on-windows) using Visual Studio 2008 (which is the only commercial product available here) but even the most basic example would fail to build.

回答1:

I've successfully compiled C extensions for Python on 64-bit Windows before by running the following commands from the "Visual Studio 2008 x64 Win64 Command Prompt" in the top level directory of the source distribution of the extension:

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


回答2:

I'd use Shed Skin: Just download, unzip, run the init bat, and compile your Python code.

If that doesn't work, and you can get Microsoft's C compiler environment working, try Cython. This tutorial compares a normal Python extension with its generated C version. Updated excerpts:

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}
)

compile:

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)


标签: python c 64bit