---
title: "用 C 为 Python 写个简单的模块"
author: "cloudhe"
date: "2008-08-15T14:09:41Z"
tags: []
slug: "c-python"
draft: false
lastmod: "2008-08-15T14:09:41Z"
id: 228357
url: "https://cloudhe.iteye.com/blog/228357"
---

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 在哪里（的位置？- cloud），有可能你的在 -L/usr/local/lib，这个都根据实际情况。  
来测试测试，在 hello.so 的当前路径下：

```
>>> 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 的文件。

 

From [http://www.pythonid.com/html/fenleiwenzhang/extend/20070910/186.html](http://www.pythonid.com/html/fenleiwenzhang/extend/20070910/186.html)