C语言程序转换为Python语言

时间:2024-01-05 16:03:07

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, , NULL}
}; void
inithello(void)
{
Py_InitModule("hello", hello_methods);
}

二、先说说在linux怎么编译它:
很简单,只需要一个命令,

gcc -shared -fPIC hello.c -I/usr/include/python2./ -L/usr/lib -lpython2. -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:, Jan , ::)
[GCC 3.2. (Red Hat Linux 3.2.-)] 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的文件。