extending python with c

c_fib.c

#include <Python.h>

int Cfib(int n)
{
    if (n < 2) {
        return n;
    } else {
        return Cfib(n-1) + Cfib(n-2);
    }
}

static PyObject* fib(PyObject* self, PyObject* args)
{
    int n;
    if (!PyArg_ParseTuple(args, "i", &n)) {
        return NULL;
    }
    return Py_BuildValue("i", Cfib(n));
}

static PyObject* version(PyObject* self) 
{
    return Py_BuildValue("s", "Version 1.0");
}

static PyMethodDef myMethods[] = {
    {"fib", fib, METH_VARARGS, "Calculates the Fibonacci number."},
    {"version", (PyCFunction)version, METH_NOARGS, "Returns the version."},
    {NULL, NULL, 0, NULL}
};

PyMODINIT_FUNC initc_fib(void)
{
    (void)Py_InitModule("c_fib", myMethods);
}

setup.py

from distutils.core import setup, Extension

module = Extension('myModule', sources = ['myModule.c'])

setup(name='PackageName',
        version='1.0',
        description='This is a package for myModule',
        ext_modules=[module])

install mingw gcc.exe

python setup.py build

posted @ 2017-10-10 12:38  idlewith  阅读(209)  评论(0编辑  收藏  举报