美文网首页
Java Native Interface

Java Native Interface

作者: yunpxu | 来源:发表于2019-03-29 15:29 被阅读0次

All source code is available at github.

  • Create java class with native method
[yunpxu@yunpxu-mac jni]$ cat src/com/jni/HelloWorld.java 
package com.jni;

public class HelloWorld {

    static {
        System.loadLibrary("HelloWorld");
    }

    public native String sayHello(String msg);

    public static void main(String[] args) {
        new HelloWorld().sayHello("Hello JNI");
    }
}
  • Compile java and generate C header file
[yunpxu@yunpxu-mac jni]$ javac -d out/ -h src/com/jni/c  src/com/jni/HelloWorld.java
[yunpxu@yunpxu-mac jni]$ tree
.
├── jni.iml
├── out
│   └── com
│       └── jni
│           └── HelloWorld.class
└── src
    └── com
        └── jni
            ├── HelloWorld.java
            └── c
                └── com_jni_HelloWorld.h

7 directories, 4 files
  • Write HelloWorld.c
[yunpxu@yunpxu-mac jni]$ cat src/com/jni/c/HelloWorld.c 
#include <stdio.h>
#include <jni.h>
#include "com_jni_HelloWorld.h"

JNIEXPORT jstring JNICALL Java_com_jni_HelloWorld_sayHello
  (JNIEnv *env, jobject obj, jstring str) {
    printf("%s\n",(*env)->GetStringUTFChars(env, str,0));
    return str;
}
int main()
{

}
  • Generate shared library
[yunpxu@yunpxu-mac jni]$ gcc -I"$JAVA_HOME/include" -I"$JAVA_HOME/include/darwin/"  -o out/libHelloWorld.jnilib src/com/jni/c/HelloWorld.c
[yunpxu@yunpxu-mac jni]$ tree out/
out/
├── com
│   └── jni
│       └── HelloWorld.class
└── libHelloWorld.jnilib
  • Run java
[yunpxu@yunpxu-mac jni]$ cd out/ && java com.jni.HelloWorld
Hello JNI

相关文章

网友评论

      本文标题:Java Native Interface

      本文链接:https://www.haomeiwen.com/subject/yoilbqtx.html