python开发效率高,实际项目时python搭建整个项目框架,关键模块用c编写,是个不错的办法!
c函数对python的接口要按规则写。
比如一个阶乘c函数的头文件定义:
dll.h:
#ifndef LIB_H #define LIB_H extern "C" long __declspec(dllexport)factorial(int n); //接口定义 #endif
dllmain.c:
#include "dll.h" long factorial(int n){ if(n == 1)return 1; return n * factorial(n - 1); }
然后用gcc编译成dll文件。
gcc -Wall -shared dllmain.c -o dllmain.dll
或者 gcc --shared dllmain.c -o dllmain.dll
刚开始gcc提示找不到cc1.exe,在dev-cpp mingw32中有个cc1plus.exe的文件,改成cc1.exe拷贝到gcc bin目录中即可。
生成的dll就可以使用了。
from ctypes import *
#libtest=CDLL("dllmain.dll")
libtest=cdll.LoadLibrary("dllmain.dll")
print libtest.factorial(10)