4
9
2010

用C编写Python扩展的简单例子

此例子其实也就是官方的教程中的例子,详见 http://docs.python.org/extending/extending.html

但官方例子中把一段代码拆成若干个段落来解释,我自己看的时候都有点迷惑。在这里我把完整的代码贴出,并加上最简单的步骤。

 

第一步:新建一个文件夹,在里面建一个文件 spammodule.c :

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <Python.h>
 
static PyObject *
spam_system(PyObject *self, PyObject *args)
{
    const char *command;
    int sts;
 
    if (!PyArg_ParseTuple(args, "s", &command))
        return NULL;
    sts = system(command);
    return Py_BuildValue("i", sts);
}
 
static PyObject *SpamError;
 
static PyMethodDef SpamMethods[] = {
    {"system",  spam_system, METH_VARARGS,
     "Execute a shell command."},
    {NULL, NULL, 0, NULL}        /* Sentinel */
};
 
PyMODINIT_FUNC
initspam(void)
{
    PyObject *m;
 
    m = Py_InitModule("spam", SpamMethods);
    if (m == NULL)
        return;
 
    SpamError = PyErr_NewException("spam.error", NULL, NULL);
    Py_INCREF(SpamError);
    PyModule_AddObject(m, "error", SpamError);
}

第二步:建立 setup.py

 

1
2
3
4
5
6
7
8
9
10
11
12
#! /usr/bin/env python
# -*- coding: utf-8 -*-
 
from distutils.core import setup, Extension
 
module1 = Extension('spam',
                    sources = ['spammodule.c'])
 
setup (name = 'spam',
       version = '1.0',
       description = 'This is a demo package',
       ext_modules = [module1])

第三步:运行命令

 

1
python setup.py build

运行后的文件夹结构如下:

.
├── build
│   ├── lib.linux-i686-2.6
│   │   └── spam.so
│   └── temp.linux-i686-2.6
│       └── spammodule.o
├── setup.py
└── spammodule.c

测试步:

 

1
2
3
cd build/lib.linux-i686-2.6/
python -c "import spam;spam.system('ls -l')"
ls -l

后面两行命令应该显示相同的结果。

 

 

 

 

 

 

 

 

Category: 未分类 | Tags: python c

Host by is-Programmer.com | Power by Chito 1.3.3 beta | Theme: Aeros 2.0 by TheBuckmaker.com