Binding a single function symbol with [foreign]

Jorn Vernee jbvernee at xs4all.nl
Sun Sep 9 19:45:11 UTC 2018


Hello,

It turns out I was using an older build of the branch (sorry, TIL 'hg 
pull' only works for the active branch). I also applied your recent 
Callback patch, and what I was trying to do was almost already possible 
through another route.

This is the code I'm going for:

     @NativeCallback("(u64:i8)i32")
     public interface PutsCallback {
         int call(Pointer<Byte> message);
     }

     public static void main(String[] args) throws Throwable {
         Library lib = Libraries.loadLibrary(lookup(), "msvcrt");
         Symbol sym = lib.lookup("puts");

         Callback<PutsCallback> clbck = 
sym.getAddress().asCallback(PutsCallback.class);
         PutsCallback puts = clbck.asFunction();

         Scope scope = Scope.newNativeScope();
         Pointer<Byte> message = scope.toCString("Hello!");
         System.out.println(puts.call(message));
     }

Instead of passing an explicit MethodType, the method type is derived 
from the SAM of a functional interface, which also solves the problem of 
missing generic type parameters.

There were 2 changes I made when trying to make this work:

Firstly, I had to implement asCallback, which basically just creates a 
new CallbackImpl with the pointer itself as the entry point.

Secondly, the CallbackImpl::asFunction method uses the Scope of it's 
entry point, but in the case of a library symbol that scope is null, so 
it fails with an NPE. As a workaround I'm creating (and leaking) a new 
native scope in case the scope is null. Maybe a longer term solution 
could be something like library symbol pointers returning a Scope that 
is tied to the lifetime of the library itself?

The code half works; It prints the message, and then it crashes [1] but 
that might just be because I'm on windows which is not supported? At 
least I think this API is pretty nice. I haven't been able to build 
jextract yet, so thorough testing is difficult.

You've already said you're working on other things right now, but at 
least I wanted to send this for future reference.

Jorn

[1] : 
https://gist.github.com/JornVernee/dda1d3e42158dfddddb3ba60060e25ae


More information about the panama-dev mailing list