Java | Фишки и трюки
7.21K subscribers
182 photos
29 videos
6 files
40 links
Java: примеры кода, интересные фишки и полезные трюки

Купить рекламу: https://telega.in/c/java_tips_and_tricks

✍️По всем вопросам: @Pascal4eg
Download Telegram
🚀 Foreign Function & Memory API – замена JNI в Java 22

В Java 22 появился Foreign Function & Memory API, который позволяет взаимодействовать с C-библиотеками без JNI.

🤔 Зачем он нужен?

Безопаснее – нет Unsafe.
Проще – не нужно писать C-обёртки.
Быстрее – меньше накладных расходов.

📌 Пример вызова метода strlen из библиотеки C:


static long invokeStrlen(String s) throws Throwable {

try (Arena arena = Arena.ofConfined()) {

// Allocate off-heap memory and
// copy the argument, a Java string, into off-heap memory
MemorySegment nativeString = arena.allocateUtf8String(s);

// Link and call the C function strlen

// Obtain an instance of the native linker
Linker linker = Linker.nativeLinker();

// Locate the address of the C function signature
SymbolLookup stdLib = linker.defaultLookup();
MemorySegment strlen_addr = stdLib.find("strlen").get();

// Create a description of the C function
FunctionDescriptor strlen_sig =
FunctionDescriptor.of(ValueLayout.JAVA_LONG, ValueLayout.ADDRESS);

// Create a downcall handle for the C function
MethodHandle strlen = linker.downcallHandle(strlen_addr, strlen_sig);

// Call the C function directly from Java
return (long)strlen.invokeExact(nativeString);
}
}


💡 Совет: Используйте этот API для работы с нативными библиотеками вместо JNI.

#java #foreignapi #native
Please open Telegram to view this post
VIEW IN TELEGRAM
👍91