Search code examples
javacjava-native-interface

missing a step ? what needs to be filled in the argument of loadLibrary()


These are the incomplete steps that i have followed to call a native function from a java program.

  1. Wrote a java program and then compiled to the .class file
  2. From the command javah - jni i generated a header file with the same name as .class file.
  3. After that i opened a Microsoft Visual C++ Express , started a new project and set my application type to dll.

This is the java program that calls the native c method.

class HelloWorld {

private native void print();

public static void main( String args[] ) {
  new HelloWorld().print();
}

static {
  System.loadLibrary("??"); // what should i write here ?
}

}

And this is the c program

#include <jni.h>
#include <stdio.h>
#include "HelloWorld.h"

JNIEXPORT void JNICALL 
Java_HelloWorld_print( JNIEnv *env , jobject obj) {
  printf("Hello World!\n");
  return;
}

I kept the project name as jni tester and the c file name is HelloWorld.c

In the statement System.loadLibrary(??) What should be the name of the library in the argument ? (Or is there any step that i am missing before i can fill the argument of loadLibrary)

If so what is that i am missing ?


Solution

  • From that function's documentation System.loadLibrary:

    Parameters:

    libname - the name of the library.

    You pass it the name of your DLL. (That is, the DLL's filename without the .dll extension. On Unix-like systems, it would be the shared object name without the lib prefix or the .so (or .o for some platforms) extension.)

    Make sure your JVM can find the DLL in its library path. To change the library path, you can use the java.library.path system property like this:

    java -Djava.library.path=directory_where_your_dll_resides ...
    

    [Doing this and dropping the extension from the library name keeps the java side of your code as portable as possible. You'll be able to move it as-is to another platform, only needing to rebuild the JNI part for that target.]