python语言是支持用c来它写模块的,其实现有的很多模块也是用c写的。这里我做个简单的介绍。
先决条件:
1.在linux上编写,需要自己编译出python的动态连接库。也就是要有libpython2.5.so这样的东西。
2.在windows上,则需要mingw这个编译环境。其实只要你安装了Dev-Cpp就有了。当然还安装了windows版的python.
一、先把源代码帖上来,很简单,假设保存为 hello.c
#include
static PyObject *hello_echo(PyObject*self, PyObject *args, PyObject *keywds)
{char *something;if (!PyArg_ParseTuple(args, "s", &something))returnNULL;
printf("%s\n", something);
Py_INCREF(Py_None);returnPy_None;
}static PyMethodDef hello_methods[] ={
{"echo", (PyCFunction)hello_echo, METH_VARARGS | METH_KEYWORDS, "print string"},
{NULL, NULL,0, NULL}
};voidinithello(void)
{
Py_InitModule("hello", hello_methods);
}
二、先说说在linux怎么编译它:
很简单,只需要一个命令,
gcc -shared -fPIC hello.c -I/usr/include/python2