// 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 jdk.incubator.foreign.CLinker;
import jdk.incubator.foreign.FunctionDescriptor;
import jdk.incubator.foreign.LibraryLookup;
import jdk.incubator.foreign.MemoryAddress;
import jdk.incubator.foreign.MemorySegment;

public class C16 {
    public static void main(String[] args) throws Throwable {
        LibraryLookup dyn = LibraryLookup.ofLibrary("dyn");
        MethodHandle add = CLinker.getInstance().downcallHandle(dyn.lookup("add").get(),
                                                                MethodType.methodType(int.class, int.class, int.class),
                                                                FunctionDescriptor.of(CLinker.C_INT, CLinker.C_INT, CLinker.C_INT));
        MethodHandle dup = CLinker.getInstance().downcallHandle(dyn.lookup("dup").get(),
                                                                MethodType.methodType(MemoryAddress.class, MemoryAddress.class),
                                                                FunctionDescriptor.of(CLinker.C_POINTER, CLinker.C_POINTER));
        int a = 123;
        int b = 456;
        int c = (int)add.invoke(a, b);
        System.out.println(c);
        String s = "ABC";
        MemoryAddress tmp = (MemoryAddress)dup.invoke(CLinker.toCString(s).address());
        String s2 = CLinker.toJavaStringRestricted(tmp);
        CLinker.freeMemoryRestricted(tmp);
        System.out.println(s2);
    }
}
