第二十一章、 扩展Python
/* D:Python27LibExtest-1.0Extest2.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "Python.h"
int fac(int n)
{
if (n < 2) return(1);
return (n)*fac(n-1);
}
static PyObject *
Extest_fac(PyObject *self, PyObject *args)
{
int num;
if (!PyArg_ParseTuple(args, "i", &num))
return NULL;
return (PyObject*)Py_BuildValue("i", fac(num));
}
static PyMethodDef
ExtestMethods[] =
{
{ "fac", Extest_fac, METH_VARARGS },
{ NULL, NULL },
};
void initExtest()
{
Py_InitModule("Extest", ExtestMethods);
}
#!/usr/bin/env python
# D:Python27LibExtest-1.0setup.py
from distutils.core import setup, Extension
MOD = 'Extest'
setup(name=MOD, ext_modules=[
Extension(MOD, sources=['Extest2.c'])])
将Extest2.c和setup.py放入 Extest-1.0目录下
安装MinGW编译环境(mingw-get-inst-20110530.exe)
下载http://sourceforge.net/projects/mingw/
D:Python27LibExtest-1.0>python setup.py install build --compiler=mingw32
测试一下
>>> import Extest
>>> Extest.fac(10)
3628800
>>>