第一步:安装编译器
推荐使用mingw,使用最为便利,可以避免各种难以记忆和看不懂的设置。
下载只需安装其中的gcc部分即可,并且将编译器所在文件夹添加的环境变量path之下,例如:
pah = %path%;c:\minGW\bin
第二步:安装python
推荐使用pythonxy,安装最为方便,省去很多不必要的麻烦。
第三步:写一段测试代码
基本方法就是:C函数 c API 包装器,静态数组,模块初始化
//pythonc.c
#include <python.h>
#include <stdio.h>
void hello_pythoncapi(void){
printf('hello python');
}
static PyObject* pythoncapi(PyObject *self,PyObject*args){
char *inArgs = NULL;
PyArg_ParseTuple(args,'s',&inArgs);
printf('%s\n',inArgs);
hello_pythoncapi();
return PyString_FromFormat('hello PYHTON C API');
}
static PyMethodDef methods[]={
{'pythoncapi',pythoncapi,METH_VARARGS,'test python extension'},
{ NULL, NULL}
};
/*__declspec(dllexport)*/ void initpythonc(void) /*the string after 'init' must be same with code file */
{
Py_InitModule('pythonc',methods);/*the 1st parameter string must be same with code file */
}
第四步: 编译
打开cmd,并运行如下命令
gcc c:\MinGW\pythonc.c -shared -Ic:\Python27\include -Lc:\Python27\libs -lpython27 -o pythonc.pyd
图中的当前路径是c:\Python27\libs,编译成功后,pythonc.pyd将保存在这个路径下。
第五步 使用扩展库
将pythonc.pyd拷贝至python路径下的Lib\site_packages文件夹,可以使用import导出模块并调用pythoncapi()函数。
说明:
-Ic:\Python27\include 用于指明头文件python.h所在的文件夹
-Lc:\Python27\libs 和-lpython27一起指明了python c api函数库所在的文件夹与库文件名称(Windows下为libpython27.a)
参考:
http://www.linuxidc.com/Linux/2012-02/55038.htm
http://oldwiki.mingw.org/index.php/Python extensions
https://docs.python.org/2/extending/extending.html
百度搜索“就爱阅读”,专业资料,生活学习,尽在就爱阅读网92to.com,您的在线图书馆!
来源: http://www.92to.com/bangong/2017/07-03/24602154.html