Skip to content

Instantly share code, notes, and snippets.

@pramoth
Last active September 16, 2021 20:39
Show Gist options
  • Save pramoth/b79a0d016d4d9807788f4f44e0c09815 to your computer and use it in GitHub Desktop.
Save pramoth/b79a0d016d4d9807788f4f44e0c09815 to your computer and use it in GitHub Desktop.
package ffa.demo;
import jdk.incubator.foreign.CLinker;
import jdk.incubator.foreign.FunctionDescriptor;
import jdk.incubator.foreign.MemoryAddress;
import jdk.incubator.foreign.ResourceScope;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodType;
public class App {
public static void main(String[] args) throws Throwable {
final MemoryAddress printf = CLinker.systemLookup().lookup("printf").get(); // lookup native C printf function from library
MethodHandle printfMh = CLinker.getInstance().downcallHandle(
printf,
MethodType.methodType(int.class, MemoryAddress.class),// C printf represent in Java
FunctionDescriptor.of(CLinker.C_INT,CLinker.C_POINTER) // C => int printf(char*)
);
try (var scope = ResourceScope.newConfinedScope()) {
var cString = CLinker.toCString("Hello World from C world.\n", scope);
int len = (int)printfMh.invokeExact(cString.address());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment