JNI

One JNI simple example~

2018-03-01  本文已影响0人  UNCLE_CHUCK

Original link: https://stackoverflow.com/questions/18900736/what-are-native-methods-in-java-and-where-should-they-be-used

Once you see a small example, it becomes clear:

Main.java:
public class Main {
    public native int intMethod(int i);
    public static void main(String[] args) {
        System.loadLibrary("Main");
        System.out.println(new Main().intMethod(2));
    }
}
Main.c:
#include <jni.h>
#include "Main.h"

JNIEXPORT jint JNICALL Java_Main_intMethod(
    JNIEnv *env, jobject obj, jint i) {
  return i * i;
}
Compile and run:

On MacOS X

javac Main.java
javah -jni Main
gcc -I"$JAVA_HOME/include" -I"$JAVA_HOME/include/darwin" -o libMain.dylib -shared -fpic Main.c

On Windows 7 64bit, need to install MinGW64 to support GCC on 64bit system first.
https://sourceforge.net/projects/mingw-w64/files/Toolchains%20targetting%20Win64/Personal%20Builds/mingw-builds/4.9.1/threads-posix/seh/x86_64-4.9.1-release-posix-seh-rt_v3-rev0.7z/download

// Compile-only with -c flag. Output is Main.o
C:\ESE\C\JNI\smallE>gcc -c -I"%JAVA_HOME%\include" -I"%JAVA_HOME%\include\win32" Main.c
// Link into shared library "hello.dll"
C:\ESE\C\JNI\smallE>gcc -shared -o Main.dll Main.o
Output:

4

So it is clear that it allows you to:

This could be used to:

with the tradeoff of lower portability.

It is also possible for you to call Java from C, but you must first create a JVM in C: How to call Java functions from C++?

Example on GitHub for you to play with.

上一篇 下一篇

猜你喜欢

热点阅读