Use native code through JNITag(s): JNI


  • With MSVC6, create a new Win32 DLL project (simple) and call it javahowto.
  • In the same directory create a java source called JavaHowTo.java
    class JavaHowTo {
      public native String sayHello();
      static {
        System.loadLibrary("javahowto"); 
      }
    }
  • Compile the Java program and use javah utility to generate the JavaHowTo.h header file.
    javah -jni JavaHowTo
    
  • In MSVC6, add the JavaHowTo.h in your project header files
  • In the Tools - Options menu, set the include directories to include the Java JNI headers files. They are located in [jdk dir]\include and [jdk dir]\include\win32 directories
  • In the javahowto.cpp source, add
    #include "JavaHowTo.h" 
    
    JNIEXPORT jstring JNICALL Java_JavaHowTo_sayHello
      (JNIEnv *env, jobject obj) {
        return  env->NewStringUTF("Hello world");
    }
  • Select the Release configuration and build the project.
  • Copy the javahowto.dll in the same directory as the java program.
  • Create this new java program
    public class JNIJavaHowTo {
      public static void main(String[] args) {
        JavaHowTo jht = new JavaHowTo();
        System.out.println(jht.sayHello());
        }
    }
  • Compile and execute.

blog comments powered by Disqus