JNA, native code with Java, demo

To use native code with Java, JNA is easier than JNI, here is its main demo...

Java Native Access is a Java extension that allows you to use your own APIs by dynamically including library files, DLLs under Windows.
Unlike JNI, it is no longer necessary to generate code to use native functions. To use C functions, it is enough to include a file that defines them and declare the header of these functions in the interface.

We want to use the C language puts function provided by the msvcrt.dll file for Windows, we create the following interface:

package CInterface; 
       
import com.sun.jna.Library; 
       
public interface CInterface extends Library 
{ 
      public int puts(String str);
}     

We have announced the CInterface interface, which is a subclass of jna. In this interface, C functions are declared as methods. To use the puts method, just create a CInterface instance.

 CInterface demo = (CInterface) Native.loadLibrary(libName, CInterface.class); 
 demo.puts("Hello World!");

To do this, you need the following imports:

import com.sun.jna.Library; 
import com.sun.jna.Native;
import com.sun.jna.Platform;

In addition, the project should include a bookstore jna.jar.

You can download the complete project for NetBeans. It contains two sources:
- CInterface.java, which declares the above interface.
- hello.java using this interface.

To perform a demonstration:

  1. Download and install NetBeans.
  2. Download here is a project file, it is broken in the jna directory.
  3. Download the jna.jar bookstore from the Sun website and copy it to the jna directory.
  4. Load the project into NetBeans from this directory.
  5. Add jna.jar to bookstore list:
    Project Properties -> Libraries -> Add JAR/Folder.
  6. Draft.

Then enter the command line:

java -jar /jna/dist/hello.jar "Salut le Monde!"

You can add all the necessary functions to the interface if they are present in one DLL file, and create an interface for each DLL file added.

Full source code:

// JNA Demo. .fr
package CInterface;
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Platform;
public class hello
{
public static void main(String[] args)
{
String mytext = "Hello World!";
if (args.length != 1)
{
System.err.println("You can enter you own text between quotes...");
System.err.println("Syntax: java -jar /jna/dist/demo.jar \"myowntext\"");
}
else
mytext = args[0];
// Le nom est c pour Unix et msvcrt pour Windows
String libName = "c";
if (System.getProperty("os.name").contains("Windows"))
{
libName = "msvcrt";
}
// Chargement dynamique de la librairie
CInterface demo = (CInterface) Native.loadLibrary(libName, CInterface.class);
demo.puts(mytext);
}
}

Download Code

See the Githube Java Native Access project for jna.jar.