Skip to content

Instantly share code, notes, and snippets.

@louwers
Last active March 30, 2023 18:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save louwers/c72672ab0fc1d37187da8d1873205224 to your computer and use it in GitHub Desktop.
Save louwers/c72672ab0fc1d37187da8d1873205224 to your computer and use it in GitHub Desktop.
JNI Hello World on macOS
javac -h . NavitiveMethodsClass.java  # generates header
javac NavitiveMethodsClass.java Main.java
gcc -shared -I /opt/homebrew/Cellar/openjdk/19.0.2/include -o libNativeMethodsClass.jnilib NativeMethodsClass.c
java Main

The shared library must have a lib prefix and .jnilib extension on macOS.

public class Main {
public static void main(String[] args) {
NativeMethodsClass cl = new NativeMethodsClass();
cl.nonNative();
cl.nativeMethod();
}
}
#include <stdio.h>
#include "NativeMethodsClass.h"
JNIEXPORT void JNICALL
Java_NativeMethodsClass_nativeMethod(
JNIEnv* env,
jobject thisObj
) {
printf("Hello from C, now get rekt son.\n");
}
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class NativeMethodsClass */
#ifndef _Included_NativeMethodsClass
#define _Included_NativeMethodsClass
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: NativeMethodsClass
* Method: nativeMethod
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_NativeMethodsClass_nativeMethod
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
class NativeMethodsClass {
static {
System.loadLibrary("NativeMethodsClass");
}
public void nonNative() {
System.out.println("Non native method");
}
public native void nativeMethod();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment