pyx的Cython编译和连接的问题

pyx 模板的运行和测试

如果要测试 pyx 模板,可以通过编译或者动态导入:

  • 编译: setup.py,生成动态库(linux 为so文件, window pyd),可以直接被 import 引入到一个Python会话中
  • from distutils.core import setup
    from distutils.extension import Extension
    from Cython.Build import cythonize
    
    setup(
        ext_modules = cythonize([Extension("select_by_kp", ["select_by_kp.pyx"])]) )

    静态链接,比如链接使用 numpy:

    • 在 select_by_kp.pyx 中链接
    • # distutils: include_dirs = /Users/yangshujun/self/cython_build/venv/lib/python3.7/site-packages/numpy/core/include/
      
      import numpy as np
      cimport numpy as np
      from libc.stdio cimport printf
      # from cython.parallel import prange, parallel, threadid

      # distutils: include_dirs 代表:numpy 相关头文件所在的地方,# distutils: sources 代表:链接c源码的文件

    • 在 setup.py ,用过 Extension 包含需要头文件的目录
    • numpy_include = np.get_include()
      setup(
          cmdclass={'build_ext': build_ext},
          ext_modules=cythonize([Extension('select_by_kp', ["select_by_kp.pyx"], include_dirs=[numpy_include, ])]))

      或:使用export 添加路径

    • numpy_include = np.get_include()
      os.environ['CFLAGS'] = '-I{}'.format(numpy_include)
      setup(
          cmdclass={'build_ext': build_ext},
          ext_modules=cythonize([Extension('select_by_kp', ["select_by_kp.pyx"])]))
  • 通过 Pyximport 导入 Cython .pyx 文件,比如导入 primes1.pyx
  • from distutils import sysconfig
    import pyximport
    
    pyximport.install(pyimport=True, language_level=2)
    
    import primes1

    可以 这个就可以正常使用了

原文地址:https://www.cnblogs.com/spaceapp/p/12200872.html