This example takes you through the process of using native shared libraries with a Java™ application on Windows systems.
Procedure
- Create a sample application, Sample.java.
public class Sample
{
public native void printFromNative( );
public static void main( String[] args )
{
Sample sample = new Sample( );
sample.printFromNative( );
}
static
{
try
{
System.loadLibrary( "Sample" );
}
catch ( Exception e )
{
System.out.println( "ERROR: Unable to load libSample.so");
e.printStackTrace( );
}
}
}
- Compile Sample.java.
- Use javah to create a header file for
the native code.
- Create a file called Sample.c.
#include <stdio.h>
#include "Sample.h"
JNIEXPORT void JNICALL Java_Sample_printFromNative( JNIEnv * env, jobject obj )
{
printf( "Printing from native\n" );
}
- Compile Sample.c and then link and bind into a shared library that can be loaded and called dynamically from Java.
cl -Ic:\java\include -Ic:\java\include\win64 -MD -LD Sample.c -Fe Sample.dll
- -MD
- Ensures that Sample.dll is linked with the Win64 multithreaded C
library.
- -LD
- Instructs the C compiler to generate a DLL instead of a regular Win64 executable program.
- Run the Sample class.
set PATH=<path-generated-dll>;%PATH%
or
java -Djava.library.path=. Sample
The program will output:
Printing
from native
Results
You should now be able to use the same framework to access
native shared libraries from Java applications.