项目作者: Glavo

项目描述 :
Foreign Linker API Hack
高级语言: Java
项目地址: git://github.com/Glavo/foreign-hacker.git
创建时间: 2021-03-17T01:17:33Z
项目社区:https://github.com/Glavo/foreign-hacker

开源协议:Other

下载


Foreign Linker Hacker

Allows programmers to enable the Foreign Linker API without adding JVM parameters -Dforeign.restricted=permit or --ensure-native-access.

Java 16 or higher is required.

This library can’t avoid other limitations of the incubator module.
You still need to add --add-module jdk.incubator.foreign and --enable-preview options to JVM for use jdk.incubator.foreign module.

Usage:

  1. ForeignHacker.enableForeignAccess(module);

Add to your build

Download jar directly

Please visit releases.

Gradle

  1. repositories {
  2. maven { url 'https://jitpack.io' }
  3. }
  4. implementation group: 'org.glavo', name: 'foreign-hacker', version: "0.2.1"

Example

  1. import jdk.incubator.foreign.*;
  2. import org.glavo.foreign.hacker.ForeignHacker;
  3. import java.lang.invoke.MethodType;
  4. public final class Main {
  5. public static void main(String[] args) throws Throwable {
  6. ForeignHacker.enableForeignAccess(Main.class.getModule());
  7. LibraryLookup l = LibraryLookup.ofDefault();
  8. var handle = CLinker.getInstance().downcallHandle(
  9. l.lookup("strlen").orElse(null),
  10. MethodType.methodType(int.class, MemoryAddress.class),
  11. FunctionDescriptor.of(CLinker.C_INT, CLinker.C_POINTER)
  12. );
  13. try (MemorySegment str = CLinker.toCString("str")) {
  14. System.out.println((int) handle.invokeExact(str.address()));
  15. }
  16. }
  17. }