python 嵌入 C/C++方法

来源:互联网 发布:数据库实体是什么 编辑:程序博客网 时间:2024/06/06 05:35

摘要:利用 gcc -o libpycall.so -shared -fPIC filename.c 将 C/C++文件编译成.so文件,供 python 调用

/*gcc -o libpycall.so -shared -fPIC pycall.c */#include <stdio.h>  #include <stdlib.h>  int fact(int n){    if (n <= 1)        return 1;    else        return n*fact(n-1);}
import ctypesimport timedef fact(n): #function write in python to compare    if n<=1:return 1    else:return n*fact(n-1)if __name__=='__main__':    now=time.time()    for i in range(10000):        n=fact(100)    end=time.time()    print 'the python fact takes:',end-now    ll = ctypes.cdll.LoadLibrary #call c/c++ function    lib = ll("./libpycall.so")    for i in range(10000):        n=lib.fact(100)    print 'the c fact taks:',time.time()-end
原创粉丝点击