当前位置:首页 > 操作系统 > Windows

实现python扩展的C API方法过程全纪录(windows)

第一步:安装编译器

推荐使用mingw,使用最为便利,可以避免各种难以记忆和看不懂的设置。

下载只需安装其中的gcc部分即可,并且将编译器所在文件夹添加的环境变量path之下,例如:

pah = %path%;c:minGWin

第二步:安装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
",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:MinGWpythonc.c -shared -Ic:Python27include -Lc:Python27libs -lpython27 -o pythonc.pyd

技术分享

图中的当前路径是c:Python27libs,编译成功后,pythonc.pyd将保存在这个路径下。

第五步 使用扩展库

将pythonc.pyd拷贝至python路径下的Libsite_packages文件夹,可以使用import导出模块并调用pythoncapi()函数。


说明:

-Ic:Python27include 用于指明头文件python.h所在的文件夹

-Lc:Python27libs 和-lpython27一起指明了python c api函数库所在的文件夹与库文件名称(Windows下为libpython27.a)

参考:

http://www.linuxidc.com/Linux/2012-02/55038.htm

http://oldwiki.mingw.org/index.php/Python%20extensions

https://docs.python.org/2/extending/extending.html#

原文:http://my.oschina.net/u/63375/blog/373920


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!

相关教程推荐

其他课程推荐