Oct
20
2003

First Experiences with JNI

Never done any JNI before, but recently had a need, and it turns out that it’s a whole lot more straightforward than I was anticipating. In my case, I needed to make some mods to an existing Win32 DLL, so YMMV.



In a nutshell, the process goes like this:


  • Define the methods you need as public native in your Java class. These guys are just stubs to the C calls you’ll be making down the track, do don’t put in any method body (just like an interface!)

  • Define a static initializer for your class which contains a call to your relevant library: System.loadLibrary("myWinDll"); // but without the .DLL bit
  • Compile up your class so you get yourself a class file.

  • Run javah over your compiled class. Which is going to give you a header file

  • Implement the header file methods in your C source.

  • Compile it up!

  • Make sure the DLL your access is in your path… then start up your Java app!





I was doing all this in VC 6.0, and found that when I used a Debug build I generated GPFs., the release builds worked fine.



If you’re looking for a very cool JNI how-to (which is Unix-centric, but the same principles apply), check out ringlord.com.

About the Author: Glen Smith

Leave a comment

Glen Smith

About Glen

Co-author Grails in Action