python語言是支持用c來它寫模塊的,其實現有的很多模塊也是用c寫的。這里我做個簡單的介紹。
先決條件:
1.在linux上編寫,需要自己編譯出python的動態連接庫。也就是要有libpython2.5.so這樣的東西。
2.在windows上,則需要mingw這個編譯環境。其實只要你安裝了Dev-Cpp就有了。當然還安裝了windows版的python.
一、先把源代碼帖上來,很簡單,假設保存為 hello.c
#include <Python.h> static PyObject * hello_echo(PyObject *self, PyObject *args, PyObject *keywds) { char *something; if (!PyArg_ParseTuple(args, "s", &something)) return NULL; printf("%s\n", something); Py_INCREF(Py_None); return Py_None; } static PyMethodDef hello_methods[] = { {"echo", (PyCFunction)hello_echo, METH_VARARGS | METH_KEYWORDS, "print string"}, {NULL, NULL, 0, NULL} }; void inithello(void) { Py_InitModule("hello", hello_methods); }
二、先說說在linux怎么編譯它:
很簡單,只需要一個命令,
gcc -shared -fPIC hello.c -I/usr/include/python2.5/ -L/usr/lib -lpython2.5 -o hello.so
就可以生成 hello.so 。注意這里-I/usr/include/python2.5/ 是python的頭文件路徑,有可能你的在-I/usr/local/include/python2.5/,
-L/usr/lib 是python的libpython2.5.so在哪里,有可能你的在-L/usr/local/lib,這個都根據實際情況。
來測試測試,在hello.so的當前路徑下:
[zhaowei@papaya python]$ python Python 2.5 (r25:51908, Jan 15 2007, 09:14:22) [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import hello >>> hello.echo("hehe, hello") hehe, hello >>>
三、再來說說在windows下怎么編譯。你必須安裝有mingw,簡單來說安裝有Dev-Cpp,然后把它安裝目錄下的bin目錄加到環境變量的PATH里。
比如我的就是把D:\Dev-Cpp\bin加到PATH里。
開始了,打開命令行窗口,到hello.c所在目錄,也運行一個命令,
gcc -shared hello.c -IC:\Python25\include -LC:\Python25\libs -lpython25 -o hello.pyd
就會在當前目錄下生成一個hello.pyd的文件。