Thursday, July 26, 2007

Accessing native libraries from java

I have been toying around with a small Java project where I have had for long the need to access information about Windows (tm) controlled windows from my Java application. Also I sought after the ability able to use Window's own 'native' graphical libraries.

For long I thought I would be doomed to write my own native methods in c++/c# and use JNI to access them from Java. I haven't coded c++ for years. Thus the project stalled badly and I didn't pay attention to it for almost a year.

However yesterday I ran into some nice looking libraries that would make it much more easier for me. Both of them have kind of a similar approach where a native library can be exposed to java by creating an interface class with some native methods. The native libraries return and parameter types are automatically marshalled by the libraries too.

Of course there is some manual stuff that needs to be done, but both of them look quite nice and enable one to do quite nice things. For example have you ever seen a java window like this:

Shaped Window Demo from JNA's site

JNA (Java Native Access) seems to be more finished, has support for native libraries of Linux (x86), Mac OS X (PPC and x86), and w32+gcc and has more features than NLink. But be sure to check both!

1 comment:

Assfish said...

Tulipa katottua tota JNA:kin. Ymmärrän kyllä tuskan kirjoittaa JNI koodia, mutta tuossa JNA:ssa näyttäisi (noin nopsasti katsottuna) kerääntyvän yhteen kaikki Java:n/JNI:n performanssiongelmat. Lisäksi en oikein usko sen toimivuuteen 32-bit ja 64-bit ympäristöissä (esim. heti alkumetreillä eräs parametri oli tyyppiä int, joka taasen on 32-bit arkkitehtuurissa 4 tavua ja 64-bit arkkitehtuurissa 8 tavua). Se mikä JNI:ssä maksaa on "rajanylitys" (C->Java tahi Java/C) ja nyt tällä kirjastollahan niitä saadaan aikaan läjäpäin. Lisäksi tuettujen alustojen joukosta puuttuu eräs erittäin tärkeä ja jos ei sitä ole, niin mitäs teet?

Leikkiprojektit saattavat olla tietenkin asia erikseen ...