Java Magazine, July/August 2016
ORACLE COM JAVAMAGAZINE JULY AUGUST 2016 69 jvm languages require ffi module POSIX extend FFI Library attach_ function getuid getuid uint attach_ function getpid getpid uint end pid uid POSIX getpid POSIX getuid puts Process pid running as user uid In this example Ive created a Ruby module to hold native function bindings Think of a module as an interface with default implementations for every method Those methods can be class methods similar to static methods in Java or instance methods that are added to a class hierarchy when the module is included similar to implementing an interface in Java Inside the LibC module in the next listing I extend the FFI Library module which injects other FFI methods I can use to bind functions and define native data types Now I have access to attach_ function from the previous listing which takes as arguments the name of the function I want to call an optional Ruby name to assign to the function and information about parameter types Thats it Run this code on JRuby and youll see the real live process ID and user ID for the host JVM something thats not possible to do with pure Java code class Timeval FFI Struct layout tv_ sec ulong tv_ usec ulong end module LibC extend FFI Library attach_ function gettimeofday pointer pointer int end t Timeval new LibC gettimeofday t pointer nil puts t tv_ sec t tv_ sec t tv_ usec t tv_ usec JRubys FFI also provides a way to define native data types such as structs In the preceding code I define a Timeval struct that has an in memory layout of two unsigned longs tv_ sec and tv_ usec I bind in the libc gettimeofday function construct a new instance of Timeval and make the call The native call populates a native struct that I can then read from like a normal Ruby object all without writing a line of C code Pretty cool right FFI is capable of much more than this and there are many large production apps out there leveraging JRubys native capabilities For more information stop by the Ruby FFI project The Future of JRuby 9000 JRuby 9000 represents one of the most advanced JVM language implementations available It has its own bytecode like intermediate representation an optimizing compiler and a mixed mode interpreter plus a JIT compiler very much like the JVM itself The JRuby team has been pushing the limits of what a language can do atop the JVM In fact JRuby is currently the fastest Ruby implementation available By the end of this year the team hopes to utilize its internal representation IR runtime to make all JRuby code perform comparably to equivalent Java code without sacrificing any of Rubys unique features But the JRuby team is not stopping there In late 2014 the team partnered with Oracle Labs to open source their Truffle based Ruby implementation as part of the JRuby project Trufle is a next generation language runtime that
You must have JavaScript enabled to view digital editions.