项目作者: Gyumeijie

项目描述 :
Simple jni demo
高级语言: Shell
项目地址: git://github.com/Gyumeijie/jni.TRY.git
创建时间: 2019-09-13T05:44:45Z
项目社区:https://github.com/Gyumeijie/jni.TRY

开源协议:

下载


JNI HelloWorld

1 Define your native methods using the native modifier.

  1. public class HelloJNI {
  2. // Declare a native method sayHello() that receives nothing and returns void
  3. private native void sayHello();
  4. }

2 Generate your .h header files from the Java.

  1. javac HelloJNI.java
  2. javah -jni -classpath . HelloJNI

Or

  1. javac -h . HelloJNI.java

3 Implement your methods in a .c file.

  1. #include "HelloJNI.h"
  2. #include <jni.h>
  3. #include <stdio.h>
  4. // Implementation of native method sayHello() of HelloJNI class
  5. JNIEXPORT void JNICALL Java_HelloJNI_sayHello(JNIEnv *env, jobject thisObj)
  6. {
  7. printf("Hello JNI\n");
  8. return;
  9. }

4 Build your native library, this will vary between platforms.

  1. gcc -I$JAVA_HOME/include -I$JAVA_HOME/include/darwin HelloJNI.c -shared -o libhello.dylib

MacOS 10.6 - uses .dylib extension; MacOS - older extension name “jnilib”
Linux - use .so extension; Windows — use .dll extension.

5 Loading your library.

This is traditionally done in a static block. The value you pass to loadLibrary()
is the “base” library name – no lib prefix or .so, .dylib, .jnilib or .dll extensions.

  1. public class HelloJNI {
  2. static {
  3. // Load native library at runtime
  4. // hello.dll (Windows) or libhello.so (Unixes) or libhello.dylib(mac)
  5. System.loadLibrary("hello");
  6. }
  7. // Declare a native method sayHello() that receives nothing and returns void
  8. private native void sayHello();
  9. public static void main(String[] args) {
  10. new HelloJNI().sayHello(); // invoke the native method
  11. }
  12. }

6 Running.

Alter the VM arg java.library.path

  1. java -Djava.library.path=. HelloJNI

Alter the OS library loader

  1. export LD_LIBRARY_PATH="."
  2. java -cp . HelloJNI