Created
February 28, 2025 11:53
-
-
Save tatut/66d165a6cfcb7e82439ee9b0cbabebf6 to your computer and use it in GitHub Desktop.
Using C code from Clojure via Chicory (WebAssembly)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{:paths ["."] | |
:deps {com.dylibso.chicory/runtime {:mvn/version "1.1.0"}}} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.