Skip to content

Glavo/foreign-hacker

Repository files navigation

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:

ForeignHacker.enableForeignAccess(module);

Add to your build

Download jar directly

Please visit releases.

Gradle

repositories {
    maven { url 'https://jitpack.io' }
}

implementation group: 'org.glavo', name: 'foreign-hacker', version: "0.2.1"

Example

import jdk.incubator.foreign.*;
import org.glavo.foreign.hacker.ForeignHacker;

import java.lang.invoke.MethodType;

public final class Main {
    public static void main(String[] args) throws Throwable {
        ForeignHacker.enableForeignAccess(Main.class.getModule());

        LibraryLookup l = LibraryLookup.ofDefault();
        var handle = CLinker.getInstance().downcallHandle(
                l.lookup("strlen").orElse(null),
                MethodType.methodType(int.class, MemoryAddress.class),
                FunctionDescriptor.of(CLinker.C_INT, CLinker.C_POINTER)
        );
        try (MemorySegment str = CLinker.toCString("str")) {
            System.out.println((int) handle.invokeExact(str.address()));
        }
    }
}