java-foreign
БесплатноБез исполняемых скриптовНе проверенJava Foreign Function & Memory API (JEP 442/454, finalized in JDK 22+) plus jextract tool. Replaces JNI for calling C libraries from JVM/Kotlin without…
от claude-dev-suite★ 51 звезда на GitHubОб этом скилле
Java Foreign Function & Memory API (Project Panama)
Deep Knowledge: Use
mcp__documentation__fetch_docswith technology:java-ffmorpanama.
Why FFM API (Replacing JNI)
JNI has been Java's native interop since Java 1.1 — and is universally hated:
- Brittle C glue code, manual memory management
- Type marshaling overhead per call
- Poor IDE support
- One stack trace bug = JVM crash
Foreign Function & Memory API (FFM, finalized in JDK 22 via JEP 454) replaces JNI for most use cases:
- Pure Java/Kotlin code calls C libraries directly
- Type-safe via
MethodHandle - Region-based memory management (
Arena) - 10-100x faster than JNI for many ops
- Generated bindings via
jextract - Works seamlessly with virtual threads
For BHODL-style desktop wallet (Compose Desktop on JVM): the way to talk to OS keyring (libsecret on Linux, Keychain on macOS via Security framework, Credential Manager on Windows via wincred).
Setup
Requires JDK 22+ for stable, JDK 21 for preview:
// build.gradle.kts
java {
toolchain {
languageVersion.set(JavaLanguageVersion.of(22))
}
}
application {
applicationDefaultJvmArgs = listOf(
"--enable-native-access=ALL-UNNAMED", // grant FFI permission
)
}
// For modular projects, declare in module-info.java:
// requires java.foreign; — built-in module
For Kotlin DSL (Compose Desktop / KMP):
kotlin {
jvm("desktop") {
compilerOptions {
jvmTarget.set(JvmTarget.JVM_22)
}
}
}
MemorySegment + Arena
Memory in FFM lives in an Arena — a scope that auto-frees memory at close:
import java.lang.foreign.*;
try (Arena arena = Arena.ofConfined()) {
// Allocate 256 bytes, zeroed
MemorySegment buffer = arena.allocate(256);
// Write
buffer.set(ValueLayout.JAVA_INT, 0, 42); // store int at offset 0
buffer.setUtf8String(8, "hello"); // C string at offset 8
// Read
int value = buffer.get(ValueLayout.JAVA_INT, 0);
String str = buffer.getUtf8String(8);
System.out.println(value + " " + str);
} // memory freed here
Arena types:
Arena.ofConfined()— single thread, deterministic free atclose()Arena.ofShared()— multi-thread, deterministic freeArena.global()— never freed (process lifetime)Arena.ofAuto()— GC-managed (avoid for large allocations)
For Kotlin (with try-with-resources via use):
import java.lang.foreign.Arena
import java.lang.foreign.MemorySegment
import java.lang.foreign.ValueLayout
Arena.ofConfined().use { arena ->
val buffer = arena.allocate(256)
buffer.set(ValueLayout.JAVA_INT, 0, 42)
val value = buffer.get(ValueLayout.JAVA_INT, 0)
println(value)
}
Calling a C Function
Example: call strlen from libc.
import java.lang.foreign.*;
import java.lang.invoke.MethodHandle;
public class HelloFFM {
public static void main(String[] args) throws Throwable {
Linker linker = Linker.nativeLinker();
SymbolLookup stdlib = linker.defaultLookup();
MethodHandle strlen = linker.downcallHandle(
stdlib.find("strlen").orElseThrow(),
FunctionDescriptor.of(ValueLayout.JAVA_LONG, ValueLayout.ADDRESS)
);
try (Arena arena = Arena.ofConfined()) {
MemorySegment cString = arena.allocateUtf8String("Hello, world!");
long len = (long) strlen.invoke(cString);
System.out.println("Length: " + len);
}
}
}
Kotlin version:
import java.lang.foreign.*
import java.lang.invoke.MethodHandle
fun main() {
val linker = Linker.nativeLinker()
val stdlib = linker.defaultLookup()
val strlen: MethodHandle = linker.downcallHandle(
stdlib.find("strlen").orElseThrow(),
FunctionDescriptor.of(ValueLayout.JAVA_LONG, ValueLayout.ADDRESS)
)
Arena.ofConfined().use { arena ->
val cString = arena.allocateUtf8String("Hello, world!")
val len = strlen.invoke(cString) as Long
println("Length: $len")
}
}
Loading External Libraries
val customLib = SymbolLookup.libraryLookup("libsecret", Arena.global())
val secretSchema = customLib.find("secret_schema_new").orElseThrow()
Path resolution:
- Linux: searches
LD_LIBRARY_PATH,/usr/lib, etc. (usesdlopen) - macOS: searches
DYLD_LIBRARY_PATH, system paths - Windows: searches
PATH,%SystemRoot%\System32, etc.
For bundled native libs:
val libPath = Path.of(System.getProperty("user.dir"), "libs", "libsecret.so")
val customLib = SymbolLookup.libraryLookup(libPath, Arena.global())
Structs
Define struct layouts using MemoryLayout:
import java.lang.foreign.MemoryLayout
import java.lang.foreign.ValueLayout
// struct Point { int x; int y; };
val pointLayout = MemoryLayout.structLayout(
ValueLayout.J
Установить java-foreign в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
ReadGrepGlobWriteEditFAQ
Что делает скилл java-foreign?
Java Foreign Function & Memory API (JEP 442/454, finalized in JDK 22+) plus jextract tool. Replaces JNI for calling C libraries from JVM/Kotlin without writing native glue. Critical for desktop apps needing OS interop (keyring, system APIs) on Linux/macOS/Windows. Covers Linker, MethodHandle, MemorySegment, Arena, struct layout, jextract code generation, and integration with KMP desktop targets. USE WHEN: user mentions "Foreign Memory API", "FFM API", "jextract", "MemorySegment", "Linker", "java.lang.foreign", "JEP 442", "JEP 454", "JDK 22 FFI", "Java FFI no JNI", "panama", "OS keyring Java" DO NOT USE FOR: Rust ↔ Kotlin/Swift bindings - use `languages/uniffi` DO NOT USE FOR: Mobile Android JNI - use `mobile/android-native` DO NOT USE FOR: Generic Java patterns - use Java-specific skill
Как установить скилл java-foreign?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл java-foreign запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
doc-coauthoring
Guide users through a structured workflow for co-authoring documentation. Use when user wants to write documentation, proposals, technical specs, decision…
от Anthropicacademy-guide
Stop and check this skill before finishing any reply to a question about how to use Claude or a Claude product — it recommends matching courses, tutorials…
от Anthropicinternal-comms
A set of resources to help me write all kinds of internal communications, using the formats that my company likes to use. Claude should use this skill…
от Anthropicskill-development
This skill should be used when the user wants to "create a skill", "add a skill to plugin", "write a new skill", "improve skill description", "organize skill…
от Anthropic