I doubt that you will find an sbt solution for compiling C code. Even if you found an sbt plugin that compiled C code, I would be very surprised if everything was fine. Compiling native libraries is too different than compiling Scala.
To compile your C or C ++ library, I recommend CMake or Automake . None of them are perfect, but both do a good job, letting you basically declare "compile these .c or .cpp files to .so". Automake is more popular in open source projects, but CMake is much simpler. CMake also has good support for compiling on Windows if this is a requirement.
To access your native library from Scala, I recommend using JNA . It allows you to access your own code from any JVM language, including Scala. And he does it without the glue layer or code generation required by JNI .
I ported the JNA example from Java to Scala. There are a few things to note.
- Java varargs are different from Scala varargs. If you want to call a C function variable, you will have to write an interface in Java instead of Scala. But you will use this interface just as if it were written in Scala.
- I wanted this example to stay strictly in Scala, so I used
puts instead of printf in the example
- I made a pretty big port. You can do something for Scala -esque a bit.
And the code:
import com.sun.jna.{Library, Native, Platform} trait CLibrary extends Library { def puts(s: String) } object CLibrary { def Instance = Native.loadLibrary( if (Platform.isWindows) "msvcrt" else "c", classOf[CLibrary]).asInstanceOf[CLibrary] } object HelloWorld { def main(args: Array[String]) { CLibrary.Instance.puts("Hello, World"); for ((arg, i) <- args.zipWithIndex) { CLibrary.Instance.puts( "Argument %d: %s".format(i.asInstanceOf[AnyRef], arg)) } } }
On the side, itβs funny that you mention specifically, not wanting the Scala to C compiler. A recent document on compiling Scala to LLVM has been published , which would be pretty much the same as the Scala to C. compiler
leedm777
source share