Hi all,
I wanted to share some early progress I’ve made on a library for binding to C functions from Scala 3, which I’m calling Slinc (Scala link C).
It’s still a work in progress, so right now it’s only able to link to basic C functions, and it’s not well tested, but hopefully I can expand its capabilities in the coming month.
The library is powered by java 17’s foreign api incubator, a lot of macros, and cats Free
. Binding a function looks like this:
C code:
struct div_t {
int quot;
int rem;
};
div_t div(int numer, int denom);
Scala code:
type div_t = Struct {
val quot: int
val rem: int
}
val div = NativeIO.function[(Int, Int) => div_t]("div")
NativeIO.scope( //scope handles allocation, and deallocates native memory upon the end of the scope
for
result <- div(5,2)
quot = result.quot.get
rem = result.rem.get
yield println(s"quotient: $quot remainder: $rem")
).foldMap(NativeIO.impureCompiler) //only prints after compilation
There’s still a lot of work to do on it, and optimization to be done, but in my benchmarks it’s already beating JNA by a factor of ten on functions like the above, and it’s on par with JNR.