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 — Foreign Function & Memory API — java.evolved

Home / Topics / Foreign Function & Memory API
🏷 Foreign Function & Memory API 2 patterns

Topic: Foreign Function & Memory API

All Java patterns related to Foreign Function & Memory API — 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

File memory mapping

Old try (FileChannel channel = FileChannel.open(path, StandardOpenOption.READ, StandardOpenOption.WRITE)) { MappedByteBuffer buffer = channel.map( FileChannel.MapMode.READ_WRITE, 0, (int) channel.size()); // Limited to 2GB // Freed by GC, no control }
Modern FileChannel channel = FileChannel.open(path, StandardOpenOption.READ, StandardOpenOption.WRITE); try (Arena arena = Arena.ofShared()) { MemorySegment segment = channel.map( FileChannel.MapMode.READ_WRITE, 0, channel.size(), arena); // No size limit // ... } // Deterministic cleanup
hover to see modern →
JDK 22+ 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.