Skip to content

Instantly share code, notes, and snippets.

@izinin
Forked from LongClipeus/HelloJNI.java
Created May 14, 2022 16:35
Show Gist options
  • Save izinin/2c231f805ba6d56b4b83ca95cc0fc99f to your computer and use it in GitHub Desktop.
Save izinin/2c231f805ba6d56b4b83ca95cc0fc99f to your computer and use it in GitHub Desktop.
Example JNI/C++ Hello World in Ubuntu
public class HelloJNI {
static {
System.loadLibrary("hello"); // load libhello.so
}
private native void sayHello();
public static void main(String[] args) {
new HelloJNI().sayHello();
}
}
#include <iostream>
#include <jni.h>
#include "HelloJNI.h" // auto-generated by `javah HelloJNI`
using namespace std;
JNIEXPORT void JNICALL Java_HelloJNI_sayHello (JNIEnv *, jobject) {
cout << "Hello world. My name is Roboss" << endl;
return;
}

export JAVA_INC=/usr/lib/jvm/java-8-oracle/include

Step 1: compile the .class file and auto-generate a .h header file

javac -h . HelloJNI.java

Step 2: make the shared library with the name linked in said Java source, and implementing said native method

g++ -std=c++11 -shared -fPIC -I$JAVA_INC -I$JAVA_INC/linux HelloJNIImpl.cpp -o libhello.so

Step 3: run JVM with java.library.path set to include said shared library

java -Djava.library.path=. HelloJNI

Learn more

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment