数组运算加速是至关科学计算重要的领域,本节我们以一个简单函数为例,使用C语言为python数组加速. 一.Cython 本函数为一维数组修剪最大最小值 version1 @cython.boundscheck(False) @cython.wraparound(False) cpdef clip(double[:] a, double min, double max, double[:] out): ''' Clip the values in a to be between min and m…
github地址 使用Cython导入库的话,需要一下几个文件: .c:C函数源码 .h:C函数头 .pxd:Cython函数头 .pyx:包装函数 setup.py:python 本节示例.c和.h文件同『Python CoolBook』使用ctypes访问C代码_下_demo进阶即存在sample.c和sample.h两个源文件. cdef:Cython函数,只能在Cython中调用,python识别不了这个定义后面的主体,而且它后面也不仅仅接函数,class等均可,def定义的函数可以被P…
点击进入项目 这一次我们尝试一下略微复杂的c程序. 一.C程序 头文件: #ifndef __SAMPLE_H__ #define __SAMPLE_H__ #include <math.h> #ifdef __cplusplus extern "C" { #endif int gcd(int x, int y); int in_mandel(double x0, double y0, int n); int divide(int a, int b, int *remain…
点击进入项目 这里的数组要点在于: 数组结构,array.array或者numpy.array 本篇的数组仅限一维,不过基础的C数组也是一维 一.分块讲解 源函数 /* Average values in an array */ double avg(double *a, int n) { int i; double total = 0.0; for (i = 0; i < n; i++) { total += a[i]; } return total / n; } 封装函数 /* Call d…
点击进入项目 一.Python生成C语言结构体 C语言中的结构体传给Python时会被封装为胶囊(Capsule), 我们想要一个如下结构体进行运算,则需要Python传入x.y两个浮点数, typedef struct Point { double x,y; } Point; 然后对这两个浮点数解析后生成C中Point的结构体,如下, /* Create a new Point object */ static PyObject *py_Point(PyObject *self, PyObje…
GIL操作 想让C扩展代码和Python解释器中的其他进程一起正确的执行, 那么你就需要去释放并重新获取全局解释器锁(GIL). 在Python接口封装中去释放并重新获取全局解释器锁(GIL),此时本段程序失去GIL运行,其他线程可以无视本函数的运行而运行,直到Py_END_ALLOW_THREADS: #include "Python.h" ... PyObject *pyfunc(PyObject *self, PyObject *args) { ... Py_BEGIN_ALLO…
点击进入项目 一.C层面模块添加API 我们仍然操作如下结构体, #include <math.h> typedef struct Point { double x,y; } Point; 本节目标是封装两个Point结构体的操作函数为sample库的C级API,可以被sample以外的C库调用,首先写出以下函数指针结构体实例, /* pysample.c */ static PyObject *PyPoint_FromPoint(Point *p, int must_free) { /* 胶…
点击进入项目 一.C语言运行pyfun的PyObject对象 思路是在C语言中提供实参,传给python函数: 获取py函数对象(PyObject),函数参数(C类型) 获取GIL(PyGILState_Ensure) 确保fun对象可调用 参数转换为python对应类型(Py_BuildValue) 调用python函数(PyObject_Call) 确定调用无异常 检查返回值 释放GIL(PyGILState_Release) 异常处理 #include "Python.h" /*…
一.字典元素排序 dict.keys(),dict.values(),dict.items() 结合max.min.sorted.zip进行排序是个很好的办法,另外注意不使用zip时,字典的lambda操作方法: price = { 'a':1, 'b':2, 'c':3 } # 多个键的值相同时会采取元组比较的形式,实际应用时注意 min_p = min(zip(price.values(), price.keys())) max_p = max(zip(price.values(), pri…
一.动态库文件生成 源文件hello.c #include "hello.h" #include <stdio.h> void hello(const char *name) { printf("Hello %s!\n", name); } int factorial(int n) { if (n < 2) return 1; return factorial(n - 1) * n; } /* Compute the greatest common…