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

第一步:安装编译器php

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

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

pah = %path%;c:\minGW\binlinux

第二步:安装pythonapi

推荐使用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 */
}

第四步: 编译spa

打开cmd,并运行以下命令code

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%20extensions

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

相关文章
相关标签/搜索