Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/wapython
Path: blob/main/python/python-wasm/src/extension/hellomodule.c
1067 views
1
#include <Python.h>
2
#include <unistd.h>
3
4
static PyObject *hello(PyObject *self, PyObject *args) {
5
const char *name;
6
if (!PyArg_ParseTuple(args, "s", &name)) {
7
return NULL;
8
}
9
printf("Hello %s, from C!\n", name);
10
Py_RETURN_NONE;
11
}
12
13
static PyObject *add389(PyObject *self, PyObject *args) {
14
const long n;
15
if (!PyArg_ParseTuple(args, "l", &n)) {
16
return NULL;
17
}
18
return PyLong_FromLong(n + 389);
19
}
20
21
long gcd(long a, long b) {
22
long c;
23
long a0 = a;
24
long b0 = b;
25
while (b0 != 0) {
26
c = a0 % b0;
27
a0 = b0;
28
b0 = c;
29
}
30
return a0;
31
}
32
static PyObject *gcd_impl(PyObject *self, PyObject *args) {
33
const long n, m;
34
if (!PyArg_ParseTuple(args, "ll", &n, &m)) {
35
return NULL;
36
}
37
return PyLong_FromLong(gcd(n, m));
38
}
39
40
41
42
static PyMethodDef module_methods[] = {
43
{"hello", _PyCFunction_CAST(hello), METH_VARARGS, "Say hello to you."},
44
{"add389", _PyCFunction_CAST(add389), METH_VARARGS, "Add 389 to a C long."},
45
{"gcd", _PyCFunction_CAST(gcd_impl), METH_VARARGS, "GCD of two C longs."},
46
{NULL, NULL, 0, NULL}};
47
48
static int module_clear(PyObject *module) { return 0; }
49
50
static void module_free(void *module) { module_clear((PyObject *)module); }
51
52
struct PyModuleDef _hellomodule = {
53
.m_name = "hello",
54
.m_methods = module_methods,
55
.m_clear = module_clear,
56
.m_free = module_free,
57
};
58
59
PyMODINIT_FUNC PyInit_hello(void) {
60
// printf("PyInit_hello\n");
61
// initialize the module:
62
return PyModuleDef_Init(&_hellomodule);
63
}
64