Download Java Native Interface Tutorial

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Java Native Interface
Tutorial
Xiaolin Li
Rutgers
2/20/2004
Rutgers University Excellence Campaign
Motivation
• A seamless bridge between Java and
native implementation in C, C++ or other
languages
Java Application
and Library
Native Application
And Library
JVM
JNI
Host Environment
(OS)
Rutgers University Excellence Campaign
2
Getting Started
1. Create a Java
class that declares
the native method
Hello.h
4. Write C impl
5. Compile C code
and generate
native lib
Hello.java
3. Javah –jni
Hello
Hello.c
2. Compile
(javac)
Hello.class
6. Done
Run the java
application
Java Hello
Hello.dll
or libhello.so
Rutgers University Excellence Campaign
3
Hello World
// Hello.java
public class Hello {
static {
String libpath =
System.getProperty("java.library.path");
libpath += ":.";
System.setProperty("java.library.path", libpath);
System.loadLibrary("Hello");
}
public static void main(String[] args) {
Hello hello = new Hello();
hello.Hello();
}
private native void Hello();
}
Rutgers University Excellence Campaign
4
Hello World
// Hello.c
#include <stdio.h>
#include <math.h>
#include "Hello.h"
JNIEXPORT void JNICALL Java_Hello_hello(JNIEnv*
env, jobject obj)
{
printf("Hello, World.\n");
}
Rutgers University Excellence Campaign
5
Executable Java Application
int main(int argc, char * argv[])
{
JNIEnv *env;
JavaVM *jvm;
jint res;
jclass cls;
jmethodID mid;
// 1. create JVM
res = JNI_CreateJavaVM(&jvm, (void**) &env, &vm_args);
// 2. find and load the Java application
cls = (*env)->FindClass(env, "Hello");
mid = (*env)->GetStaticMethodID(env, cls, "main",
"([Ljava/lang/String;)V");
// 3. execute it
(*env)->CallStaticVoidMethod(env, cls, mid, args);
(*jvm)->DestroyJavaVM(jvm);
}
Rutgers University Excellence Campaign
6
Thank You
2/20/2004
Rutgers University Excellence Campaign
Related documents