refactor: curate hello world sample

Remove noisy bits
This commit is contained in:
exaucae 2022-11-12 00:21:08 +00:00
parent 576f9c9eaf
commit 7e1a06e2e6
1 changed files with 8 additions and 13 deletions

View File

@ -13,30 +13,25 @@ public class HelloWorld {
public static void main(String[] args) throws Throwable { public static void main(String[] args) throws Throwable {
String symbolName = "printf"; String symbolName = "printf";
String greetings = "Hello World from Project Panama Baeldung Article"; String greeting = "Hello World from Project Panama Baeldung Article";
Linker nativeLinker = Linker.nativeLinker(); Linker nativeLinker = Linker.nativeLinker();
SymbolLookup stdlibLookup = nativeLinker.defaultLookup(); SymbolLookup stdlibLookup = nativeLinker.defaultLookup();
SymbolLookup loaderLookup = SymbolLookup.loaderLookup(); SymbolLookup loaderLookup = SymbolLookup.loaderLookup();
FunctionDescriptor functionDescriptor = FunctionDescriptor.of( FunctionDescriptor descriptor = FunctionDescriptor.of(JAVA_INT, ADDRESS);
JAVA_INT.withBitAlignment(32),
ADDRESS.withBitAlignment(64)
);
MethodHandle methodHandle = MethodHandle methodHandle = loaderLookup.lookup(symbolName)
loaderLookup.lookup(symbolName)
.or(() -> stdlibLookup.lookup(symbolName)) .or(() -> stdlibLookup.lookup(symbolName))
.map( .map(symbolSegment -> nativeLinker.downcallHandle(symbolSegment, descriptor))
symbolAddress -> nativeLinker.downcallHandle(symbolAddress, functionDescriptor) .orElse(null);
).orElse(null);
Objects.requireNonNull(methodHandle); Objects.requireNonNull(methodHandle);
try (MemorySession memorySession = MemorySession.openConfined()) { try (MemorySession memorySession = MemorySession.openConfined()) {
MemorySegment nativeGreetings = memorySession.allocateUtf8String(greetings + "\n"); MemorySegment greetingSegment = memorySession.allocateUtf8String(greeting);
methodHandle.invoke(nativeGreetings); methodHandle.invoke(greetingSegment);
} }
} }
} }