https://github.com/glavo/foreign-hacker
Foreign Linker API Hack
https://github.com/glavo/foreign-hacker
ffi java jni panama
Last synced: 9 months ago
JSON representation
Foreign Linker API Hack
- Host: GitHub
- URL: https://github.com/glavo/foreign-hacker
- Owner: Glavo
- License: other
- Created: 2021-03-17T01:17:33.000Z (over 5 years ago)
- Default Branch: main
- Last Pushed: 2021-09-19T12:34:16.000Z (almost 5 years ago)
- Last Synced: 2025-03-03T06:27:25.280Z (over 1 year ago)
- Topics: ffi, java, jni, panama
- Language: Java
- Homepage:
- Size: 69.3 KB
- Stars: 6
- Watchers: 3
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Foreign Linker Hacker
[](https://jitpack.io/#Glavo/foreign-hacker)
Allows programmers to enable the [Foreign Linker API](https://openjdk.java.net/jeps/389) 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:
```java
ForeignHacker.enableForeignAccess(module);
```
## Add to your build
### Download jar directly
Please visit [releases](https://github.com/Glavo/foreign-hacker/releases/latest).
### Gradle
```groovy
repositories {
maven { url 'https://jitpack.io' }
}
implementation group: 'org.glavo', name: 'foreign-hacker', version: "0.2.1"
```
## Example
```java
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()));
}
}
}
```