GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • java.evolved

This view

  • Original page
  • New address

GeezerVison is showing javaevolved.dev — Native Code — java.evolved

Home / Topics / Native Code
🏷 Native Code 2 patterns

Topic: Native Code

All Java patterns related to Native Code — java.evolved

Language

Calling out to C code from Java

Old public class CallCFromJava { static { System.loadLibrary("strlen-jni"); } public static native long strlen(String s); public static void main(String[] args) { long ret = strlen("Bambi"); System.out.println("Return value " + ret); // 5 } } // Run javac -h to generate the .h file, then write C: // #include "CallCFromJava.h" // #include <string.h> // JNIEXPORT jlong JNICALL Java_CallCFromJava_strlen( // JNIEnv *env, jclass clazz, jstring str) { // const char* s = (*env)->GetStringUTFChars(env, str, NULL); // jlong len = (jlong) strlen(s); // (*env)->ReleaseStringUTFChars(env, str, s); // return len; // }
Modern void main() throws Throwable { try (var arena = Arena.ofConfined()) { // Use any system library directly — no C wrapper needed var stdlib = Linker.nativeLinker().defaultLookup(); var foreignFuncAddr = stdlib.find("strlen").orElseThrow(); var strlenSig = FunctionDescriptor.of(ValueLayout.JAVA_LONG, ValueLayout.ADDRESS); var strlenMethod = Linker.nativeLinker() .downcallHandle(foreignFuncAddr, strlenSig); var ret = (long) strlenMethod.invokeExact(arena.allocateFrom("Bambi")); System.out.println("Return value " + ret); // 5 } } // Your own C library needs no special Java annotations: // long greet(char* name) { // printf("Hello %s\n", name); // return 0; // }
hover to see modern →
JDK 22+ learn more →
I/O

Finalizers to deterministic resource cleanup

Old @Override protected void finalize() throws Throwable { nativeHandle.release(); }
Modern final class NativeResource implements AutoCloseable { private static final Cleaner CLEANER = Cleaner.create(); private static final class State implements Runnable { private final long handle; State(long handle) { this.handle = handle; } @Override public void run() { release(handle); } } private final Cleaner.Cleanable cleanable; NativeResource(long handle) { cleanable = CLEANER.register(this, new State(handle)); } @Override public void close() { cleanable.clean(); } }
hover to see modern →
JDK 9+ learn more →
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.