Python和C|C++的混编(二):利用Cython进行混编

还能够使用Cython来实现混编

1 下载Cython。用python setup.py install进行安装

2 一个实例

① 创建helloworld文件夹

创建helloworld.pyx,内容例如以下:

cdef extern from"stdio.h":

    extern int printf(const char *format, ...)

def SayHello():

printf("hello,world ")

编译,最方便的是利用python的Distutils了,

helloworld文件夹下创建Setup.py,内容例如以下:

from distutils.core import setup

from distutils.extension import Extension

from Cython.Build import cythonize

 

setup(

  name = 'helloworld',

  ext_modules=cythonize([

    Extension("helloworld", ["helloworld.pyx"]),

    ]),

)

 

编译:

python Setup.py build

安装:

python Setup.py install

安装后。会将在build/lib.??

?文件夹下生成的helloworld.pyd复制到Lib/site-packages

注:

  有时我们仅仅是希望測试一下。并不希望安装。这时能够把build/lib.???文件夹下的helloworld.pyd复制到当前文件夹

  或者在importhelloworld前运行脚本:import sys;sys.path.append(pathof helloworld.pyd)

 

③ 測试:

>>>import helloworld

>>>helloworld.SayHello()

hello,world

原文地址:https://www.cnblogs.com/yutingliuyl/p/7015698.html