Hi Everyone,
I want to call native functions in a C-Library from Clojure via JNR-FFI without having to write Java code.
(defproject mypkg
:dependencies [[org.clojure/clojure "1.10.1"]
[com.github.jnr/jnr-ffi "2.2.0"]])
Based on the jnr-ffi examples here and here a Java wrapper might look like
package blahblah;
public class BlahNative {
private static int[] intDummy;
private static double[] doubleDummy;
public BlahNative() {
}
public static native void native_a(char var0, char var1, int var2, int var3, int var4, double[] var7, int var8, int var9);
public static native void native_b(char var0, char var1, int var2, int var3, int var4, double[] var7, int var8, int var9);
static {
lib = LibraryLoader
.create(LibSodium.class)
.search("/usr/local/lib")
.search("/opt/local/lib")
.search("/usr/lib")
.search("/lib")
.load(LIBRARY_NAME);
initializeLibrary(lib);
}
}
I presume my Clojure namespace should use the gen-class feature for implementing Java classes.
(ns mypkg.native
(:import [jnr.ffi LibraryLoader])
(:import [jnr.ffi.annotations IgnoreError])
(:import [jnr.ffi.provider FFIProvider])
(:gen-class))
Then,
How do I write a native method in Clojure? In other words, do I even need to specify the method type (as native
) when using Clojure's Java interop features?
After loading the native library I do not know how to access the C-functions in the library. How do I do it?
To avoid reloading the library for every Clojure wrapper function of each C-functions, can I write a method like
(defn lib (. LibraryLoader load LIBRARY_NAME))
and then access the native functions in it?
I am neither a C nor a Java expert so any guidance will be much appreciated.
Thanks.