Running C code from Java via VTCC
In one of our projects we transform C code via VMF & VMF-Text which is a powerful language modeling framework based on ANTLR4 grammars. It can parse and write (“unparse”) code that conforms to a specified grammar and provides a Java API for manipulating the model. In one of our applications we use this infrastructure to add source-based instrumentations to a subset of C.
The problem is running and testing C code without requiring a (manually installed) native Compiler. On macOS and Windows this can involve downloading several GB for Xcode and Visual Code. There are smaller alternatives. But even they require additional installation and path adjustments. For on-the-fly execution of C code this is overkill.
To test and execute the C code hassle-free, I worked on a small Java library VTCC which uses the TCC compiler to run C code directly from Java. To prevent the JVM from crashing the code runs in its own process (for now, JNI integration might follow at some point).
VTCC embedds a tiny C compiler (< 1MB) to compile and run the C code snippets (works for Linux, macOS and Windows on x86 & x64). The API is fairly simple. Here’s an example:
The code is hosted on GitHub: https://github.com/miho/VTCC/. Binary distributions with an embedded compiler for Linux, macOS and Windows are available via bintray (maven central&jcenter). For an out-of-the-box experience you need two dependencies, the VTCC library and the binary dependency.
VTCC:
tcc-dist:
Example (Gradle):
dependencies {
// core library
compile 'eu.mihosoft.vtcc:vtcc:2018.1.3'
// binary dependencies
compile 'eu.mihosoft.vtcc.tccdist:tcc-dist:2018.1.3'
}
We are also going to add this library as plugin for VRL-Studio to finally add C support (for a subset of C).
There are many features that could be implemented on top of this like JNI support or shared memory between the JVM and native processes. If you have ideas don’t hesitate to contact me!
Stay tuned and follow me on Twitter
Leave a Reply