収穫

pyrex で xosd を使わないで Mac で .so を作る

ソースコード

primes.py

def primes(int kmax):
    cdef int n, k, i
    cdef int p[1000]
    result = []
    if kmax > 1000:
        kmax = 1000
    k = 0
    n = 2
    while k < kmax:
        i = 0
        while i < k and n % p[i] <> 0:
            i = i + 1
        if i == k:
            p[k] = n
            k = k + 1
            result.append(n)
        n = n + 1
    return result

setup.py

from distutils.core import setup, Extension
from Pyrex.Distutils import build_ext

PRIMES_EXT_MODULES = [
  Extension("primes", ["primes.pyx"]),
  ]

setup(
  name="primes",
  version="1.0",
  ext_modules=PRIMES_EXT_MODULES,
  cmdclass={'build_ext': build_ext}
  )

$ python setup.py build
$ cd build/lib.macosx-10.4-i386-2.5
$ ls
primes.so
$ python

>>> import primes
>>> primes.primes(10)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]