Requires Free Membership to View
To use a native library from the JNI subsystem, you must:
A) Prototype the native routines, rebuild the library and place it in the JDK's runtime path
B) Implement Java-to-C and C-to-Java data conversions
C) Load the library from Java using the System.loadLibrary method
D) Declare the native routines to Java
The following example demonstrates JNI prototypes for C routines:
JNIEXPORT void JNICALL Java_MyJavaClass_myNativeRoutine (JNIEnv *, jclass, jstring); JNIEXPORT jboolean JNICALL Java_MyJavaClass_myNextNativeRoutine (JNIEnv *, jclass);The following example demonstrates a conversion from a Java String to a C string:
JNIEXPORT jboolean JNICALL Java_MyJavaClass_myNativeRoutine
( JNIEnv *env, jobject obj, jstring jParam)
{
/* convert the Java String param */
const char *cParam = (*env)->GetStringUTFChars(env,
jParam, 0);
/* use the string */
makeAnActualNativeCall(cParam);
/* free the memory used by the C string */
(*env)->ReleaseStringUTFChars(env, jParam,
cParam); }
A complete list of data-type conversions and their usage can be found at: http://java.sun.com/j2se/1.3/docs/guide/jni/index.htmlThe following example demonstrates the loadLibrary method and examples of native routine declarations:
class MyJavaClass
{
static
{
try
{
// load the native
library
System.loadLibrary"mylibrary");
}
catch( UnsatisfiedLinkError e)
{
System.out.println("Error loading native library");
}
}
// declare the native routines
public static native void myNativeRoutine(String aParam);
public static native boolean myNextNativeRoutine();
}
Once the library is loaded, you can make calls to-and-from
Java and the native library. This was first published in February 2004

Join the conversationComment
Share
Comments
Results
Contribute to the conversation