-
Notifications
You must be signed in to change notification settings - Fork 9
/
fibmodule.c
51 lines (44 loc) · 1.08 KB
/
fibmodule.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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <Python.h>
int _fib(int n)
{
printf("Debug: calling _fib(%d)\n", n);
if (n <= 1)
return n;
else
return _fib(n-1) + _fib(n-2);
}
/* Wrapped _fib function */
static PyObject* fib(PyObject* self, PyObject* args)
{
int n;
/* Parse the input, from Python integer to C int */
if (!PyArg_ParseTuple(args, "i", &n))
return NULL;
/* If the above function returns -1, an appropriate Python exception will
* have been set, and the function simply returns NULL
*/
/* Construct the result: a Python integer object */
return Py_BuildValue("i", _fib(n));
}
/* Define functions in module */
static PyMethodDef FibMethods[] = {
{"fib", fib, METH_VARARGS, "Calculate the Fibonacci numbers (in C)."},
{NULL, NULL, 0, NULL} /* Sentinel */
};
/* Create PyModuleDef structure */
static struct PyModuleDef fibStruct = {
PyModuleDef_HEAD_INIT,
"fib",
"",
-1,
FibMethods,
NULL,
NULL,
NULL,
NULL
};
/* Module initialization */
PyObject *PyInit_fib(void)
{
return PyModule_Create(&fibStruct);
}