Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/wapython
Path: blob/main/python/python-wasm/src/extension/hellozigmodule.zig
1067 views
1
// We make a WASM extension to cpython with the code written in zig here
2
// and in hellozigmodule.c.
3
4
// We can implement the functions in zig, but we have to do the
5
// basic wiring in C still (in hellomodule.c), since Python extension
6
// modules involve a bunch of macros that zig can't parse. And we
7
// shouldn't just read the code and try to untagle them, since that violates
8
// the abstraction. The best thing is to have a C layer.
9
10
const std = @import("std");
11
const py = @cImport(@cInclude("Python.h"));
12
13
export fn hello(self: *py.PyObject, args: *py.PyObject) ?*py.PyObject {
14
_ = self;
15
var name: [*:0]u8 = undefined;
16
if (py.PyArg_ParseTuple(args, "s", &name) == 0) {
17
return null;
18
}
19
std.debug.print("Hello {s}, from Zig!\n", .{name});
20
return py.Py_NewRef(py.Py_None);
21
}
22
23
export fn add389(self: *py.PyObject, args: *py.PyObject) ?*py.PyObject {
24
_ = self;
25
var n: c_long = undefined;
26
if (py.PyArg_ParseTuple(args, "l", &n) == 0) {
27
return null;
28
}
29
return py.PyLong_FromLong(n + 389);
30
}
31
32
export fn gcd_impl(self: *py.PyObject, args: *py.PyObject) ?*py.PyObject {
33
_ = self;
34
var n: c_long = undefined;
35
var m: c_long = undefined;
36
if (py.PyArg_ParseTuple(args, "ll", &n, &m) == 0) {
37
return null;
38
}
39
return py.PyLong_FromLong(gcd(n, m));
40
}
41
42
fn gcd(a: c_long, b: c_long) c_long {
43
var c: c_long = undefined;
44
var a0 = a;
45
var b0 = b;
46
while (b0 != 0) {
47
c = @mod(a0, b0);
48
a0 = b0;
49
b0 = c;
50
}
51
return a0;
52
}
53
54