Java Native Interface Tutorial - PowerPoint PPT Presentation

1 / 7
About This Presentation
Title:

Java Native Interface Tutorial

Description:

Java Native Interface Tutorial – PowerPoint PPT presentation

Number of Views:483
Avg rating:3.0/5.0
Slides: 8
Provided by: xlli
Category:

less

Transcript and Presenter's Notes

Title: Java Native Interface Tutorial


1
Java Native Interface Tutorial
  • Xiaolin Li
  • Rutgers

2
Motivation
  • A seamless bridge between Java and native
    implementation in C, C or other languages

Java Application and Library
Native Application And Library
Host Environment (OS)
3
Getting Started
1. Create a Java class that declares the native
method
2. Compile (javac)
Hello.java
3. Javah jni Hello
Hello.class
Hello.h
6. Done Run the java application Java Hello
Hello.c
4. Write C impl
5. Compile C code and generate native lib
Hello.dll or libhello.so
4
Hello World
  • // Hello.java
  • public class Hello
  • static
  • String libpath
    System.getProperty("java.library.path")
  • libpath "."
  • System.setProperty("java.library.p
    ath", libpath)
  • System.loadLibrary("Hello")
  • public static void main(String args)
  • Hello hello new Hello()
  • hello.Hello()
  • private native void Hello()

5
Hello World
  • // Hello.c
  • include ltstdio.hgt
  • include ltmath.hgt
  • include "Hello.h"
  • JNIEXPORT void JNICALL Java_Hello_hello(JNIEnv
    env, jobject obj)
  • printf("Hello, World.\n")

6
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)-gtFindClass(env, "Hello")
  • mid (env)-gtGetStaticMethodID(env, cls,
    "main", "(Ljava/lang/String)V")
  • // 3. execute it
  • (env)-gtCallStaticVoidMethod(env, cls, mid,
    args)
  • (jvm)-gtDestroyJavaVM(jvm)

7
Thank You
Write a Comment
User Comments (0)
About PowerShow.com