-
Notifications
You must be signed in to change notification settings - Fork 0
/
spammodule.c
113 lines (81 loc) · 2.37 KB
/
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#include <Python.h>
static PyObject *spam_greet(PyObject *self, PyObject *args)
{
const char *name;
if (!PyArg_ParseTuple(args, "s", &name)) return NULL;
printf("Hi %s!", name);
Py_RETURN_NONE;
}
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 *spam_strlen(PyObject *self, PyObject *args)
{
const char *string;
if (!PyArg_ParseTuple(args, "s", &string)) return NULL;
unsigned long len = strlen(string);
return Py_BuildValue("i", len);
}
PyObject *makelist(int array[], int len)
{
PyObject *py_list = PyList_New(len);
for (int i = 0; i < len; i++) {
PyList_SET_ITEM(py_list, i, Py_BuildValue("i", array[i]));
}
return py_list;
}
static PyObject *SpamError;
static PyObject *spam_fibonacci(PyObject *self, PyObject *args)
{
int num_terms;
if (!PyArg_ParseTuple(args, "i", &num_terms)) return NULL;
if (num_terms < 0) {
PyErr_SetString(SpamError, "Number of terms cannot be negative.");
return NULL;
}
int numbers[num_terms];
int first = 0;
int second = 1;
int next;
for (int i = 0; i < num_terms; i++) {
if (i <= 1) {
next = i;
} else {
next = first + second;
first = second;
second = next;
}
numbers[i] = next;
}
return makelist(numbers, num_terms);
}
static PyMethodDef SpamMethods[] = {
{"greet", spam_greet, METH_VARARGS, "Print greeting."},
{"system", spam_system, METH_VARARGS, "Execute a shell command."},
{"strlen", spam_strlen, METH_VARARGS, "Return length of a string"},
{"fibonacci", spam_fibonacci, METH_VARARGS, "Return fibonacci series."},
// ...
{NULL, NULL, 0, NULL} /* sentinel */
};
PyMODINIT_FUNC initspam(void)
{
PyObject *m = Py_InitModule("spam", SpamMethods);
if (m == NULL) return;
SpamError = PyErr_NewException("spam.error", NULL, NULL);
Py_INCREF(SpamError);
PyModule_AddObject(m, "error", SpamError);
}
int main(int argc, char *argv[])
{
// Pass argv[0] to the Python interpreter
Py_SetProgramName(argv[0]);
// Initialize the Python interpreter. Required
Py_Initialize();
// Add a static module
initspam();
}