Archive

Posts Tagged ‘dll’

Java Native Access, JNA, thoughts

In order to get system information, you almost certainly have to go to some platform specific functions. I’m referring to something that in non-trivial, the Java API is great but it really does fall short when you need to interact with OS kernel functions. The old (well older) way to do so would be to use JNI (Java Native Interface). With JNI, you would generate a client stub in Java and essentially link it to the implementation which is in C (or any other language you have bindings for). The keyword ‘native’ in Java tells the compiler of your intentions and that leads to good relative performance because the compiler is able to do static linking.

There are books written on the subject and there is not much to it but JNI is certainly a way to get Java to interact with win32 api. During developing LabelTop (see Links), I wanted to interact on a low level with the OS. I wanted to get processor usage information and memory usage information. My experience that I mention here is almost equally applicable to Mac OS X where I called Obj-C functions from the Cocoa API. I decided to use JNA instead of JNI.

JNA is a project which is (was) in incubation at java.net. It always dynamic linking with native resources. The benefit of that is that you have a lot less compile time stuff to do as a programmer. Though, the cost is that you do lose some performance. While I haven’t done a detailed empirical study of the amount of performance loss, my experience is that the loss is hardly noticeable, after having used JNA quite a bit.

A big benefit is that I’m able to represent the underlying ‘struct’ as a simple Java class, an interface with signatures of functions that I want to call in Java. I can then load a dll file that I didn’t write and call its functions. JNA will take an input the function I’m calling and its input parameters, convert the function call to a C function call and convert the class to struct, then I will execute the function using the dll, it will take the results and convert that to Java types and return them to me.

Equivalently, with JNI, I would to write my interface, declare methods as native, write my C program which would then call functions in the dll. Get the results back from dll and return them myself. So JNA, does a lot of the heavy lifting for me.

The kernel32.dll is huge! I don’t need to call every function. So in my interface I declare the functions that I will want to use and just call those. If I need another function then I can declare that in my interface too. Thus, integration can be done iteratively which saves a lot of time. JNA uses a mapping of primitive types from Java to C which is very clear and straightforward. Have fun!

Categories: Java, Java Misc Tags: , , , , ,