How to build and call native methods


Once again, there's no applet on this page; feel free to download the source and build it on your own machine. It's a fairly straightforward process if you let the makefile take care of things.

The source:
A Java application with a native method
The implementation file for the native method
The makefile; a lot of the action happens here


This is an ultra-brief, ultra-simple example of how to create a native method and call it from a Java class. The only thing the native method does is to call printf() with the string "within native method". The purpose of this example is to de-obfuscate the process of creating native methods. A later example will address passing arguments to native methods, returning values from them, etc.

Some potential problems you might have:
1) I developed this example under Windows95 using Microsoft C++. You may be using a different compiler, linker, or make utility. I don't do anything particularly fancy, so hopefully this will not cause too many problems for you.

2) I needed to add c:\java\include and c:\java\include\win32 to my INCLUDE environment variable for the generated C code to compile correctly (because the generated code #includes ). You will need to do the same. (Obviously, if you're not on a win32 platform, you'll have a different directory to include). This could also be done in the makefile, but I wanted to keep the makefile as simple as possible.

3) The DLL (or .so, or whatever) that is generated at the end of all this needs to be either in one of the directories enumerated in the environment variable LD_LIBRARY_PATH, or in the directory from which your class is being executed.