// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodType;

import java.lang.foreign.Linker;
import java.lang.foreign.FunctionDescriptor;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.SegmentScope;
import java.lang.foreign.SymbolLookup;
import java.lang.foreign.ValueLayout;

public class C20 {
    public static void main(String[] args) throws Throwable {
        System.loadLibrary("dyn");
        SymbolLookup sym = SymbolLookup.loaderLookup();
        Linker linker = Linker.nativeLinker();
        MethodHandle add = linker.downcallHandle(sym.find("add").get(),
                                                 FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.JAVA_INT, ValueLayout.JAVA_INT));
        MethodHandle dup = linker.downcallHandle(sym.find("dup").get(),
                                                 FunctionDescriptor.of(ValueLayout.JAVA_LONG, ValueLayout.ADDRESS));
        int a = 123;
        int b = 456;
        int c = (int)add.invoke(a, b);
        System.out.println(c);
        String s = "ABC";
        MemorySegment itmp = MemorySegment.allocateNative(4, SegmentScope.global());  
        itmp.setUtf8String(0, s);
        MemorySegment otmp = MemorySegment.ofAddress((long)dup.invoke(itmp), 7);
        String s2 = otmp.getUtf8String(0);
        System.out.println(s2);
    }
}
