Path: blob/main/python/python-wasm/src/extension/hellozigmodule.zig
1067 views
// We make a WASM extension to cpython with the code written in zig here1// and in hellozigmodule.c.23// We can implement the functions in zig, but we have to do the4// basic wiring in C still (in hellomodule.c), since Python extension5// modules involve a bunch of macros that zig can't parse. And we6// shouldn't just read the code and try to untagle them, since that violates7// the abstraction. The best thing is to have a C layer.89const std = @import("std");10const py = @cImport(@cInclude("Python.h"));1112export fn hello(self: *py.PyObject, args: *py.PyObject) ?*py.PyObject {13_ = self;14var name: [*:0]u8 = undefined;15if (py.PyArg_ParseTuple(args, "s", &name) == 0) {16return null;17}18std.debug.print("Hello {s}, from Zig!\n", .{name});19return py.Py_NewRef(py.Py_None);20}2122export fn add389(self: *py.PyObject, args: *py.PyObject) ?*py.PyObject {23_ = self;24var n: c_long = undefined;25if (py.PyArg_ParseTuple(args, "l", &n) == 0) {26return null;27}28return py.PyLong_FromLong(n + 389);29}3031export fn gcd_impl(self: *py.PyObject, args: *py.PyObject) ?*py.PyObject {32_ = self;33var n: c_long = undefined;34var m: c_long = undefined;35if (py.PyArg_ParseTuple(args, "ll", &n, &m) == 0) {36return null;37}38return py.PyLong_FromLong(gcd(n, m));39}4041fn gcd(a: c_long, b: c_long) c_long {42var c: c_long = undefined;43var a0 = a;44var b0 = b;45while (b0 != 0) {46c = @mod(a0, b0);47a0 = b0;48b0 = c;49}50return a0;51}525354