Created
June 12, 2020 12:13
-
-
Save saikyun/d6ac1189ea5436b7d4df6109abe25a18 to your computer and use it in GitHub Desktop.
calling c from clojure using graalvm
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
// tested using graalvm 20.2 dev | |
// https://github.com/graalvm/graalvm-ce-dev-builds/releases | |
// thanks u/duhace for https://www.reddit.com/r/java/comments/8s7sr8/interacting_with_c_using_graalvm/ | |
main.c | |
==== | |
#include <stdio.h> | |
void printHello() { | |
FILE *f = fopen("file.txt", "w"); | |
if (f == NULL) | |
{ | |
printf("Error opening file!\n"); | |
} else { | |
const char *text = "world"; | |
fprintf(f, "Hello: %s\n", text); | |
fclose(f); | |
} | |
} | |
=== | |
compile | |
$ clang -g -O1 -c -emit-llvm main.c | |
=== | |
saik/test.clj | |
=== | |
(ns saik.test | |
(:require [clojure.java.io :as io]) | |
(:import org.graalvm.polyglot.Context | |
org.graalvm.polyglot.Source)) | |
(let [s (-> (Source/newBuilder "llvm" (io/file "main.bc")) | |
(.build)) | |
c (-> (Context/newBuilder (into-array ["llvm"])) | |
(.allowIO true) | |
(.allowNativeAccess true) | |
(.build)) | |
lib (.eval c s) | |
f (.getMember lib "printHello")] | |
(.executeVoid f (into-array [""]))) ;; for some reason I was unable to call this without an array -- no clue why |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment