Skip to content

Instantly share code, notes, and snippets.

@tatut
Created February 28, 2025 11:53
Show Gist options
  • Save tatut/66d165a6cfcb7e82439ee9b0cbabebf6 to your computer and use it in GitHub Desktop.
Save tatut/66d165a6cfcb7e82439ee9b0cbabebf6 to your computer and use it in GitHub Desktop.
Using C code from Clojure via Chicory (WebAssembly)
{:paths ["."]
:deps {com.dylibso.chicory/runtime {:mvn/version "1.1.0"}}}
#include <stdio.h>
char msg[64];
char* profound(int a, int b) {
int c = a + 2*b;
if(c == 42) {
snprintf(&msg[0], 64, "DON'T PANIC");
} else {
snprintf(&msg[0], 64, "not profound: %d + 2*%d = %d", a,b,c);
}
return &msg[0];
}
// compile this file with
// $ emcc -o profound.wasm profound.c -s EXPORTED_FUNCTIONS=_profound --no-entry
(ns profound
"A very profound program."
(:require [clojure.java.io :as io])
(:import (com.dylibso.chicory.wasm Parser)
(com.dylibso.chicory.runtime Instance)
(java.io File)
(java.nio.charset Charset)))
(defonce utf-8 (Charset/forName "UTF-8"))
(def instance
(delay
(let [f (File. (.toURI (io/resource "profound.wasm")))
module (Parser/parse f)]
(.build (Instance/builder module)))))
(def profound-fn
(delay (.export @instance "profound")))
(defn profound [a b]
(let [res (aget (.apply @profound-fn (long-array [a b])) 0)]
(-> @instance .memory (.readCString res utf-8))))
(comment
;; try these
(profound 40 2)
(profound 666 1000))
@tatut
Copy link
Author

tatut commented Feb 28, 2025

Note the call interface has no marshalling, therefore the char* is returned as just a long number, which we need to know is in the wasm instance memory and call .readCString on it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment