Conversion between Java objects and native pointers
Gregory Klyushnikov
grishka93 at gmail.com
Fri Dec 2 11:20:04 UTC 2022
I'm trying to use the preview Panama API to build an FFI for Objective C, allowing Java to fully interoperate with native macOS libraries. Calling out to existing classes is simple: you just use objc_msgSend and sel_registerName a bunch with the right arguments. But many macOS APIs want you to create your own classes and override methods (NSApplicationDelegate is one example and you seemingly can't do GUI without creating one) — which isn't as easy to do in a non-ugly way with the current Panama API.
You *can* define a new Objective C class at runtime using objc_registerClassPair, but you don't have a good way of linking an ObjC object to its corresponding Java object. You can, obviously, store the pointer to the ObjC object in the Java object, but you can't do it the other way around, which poses a problem for overridden methods. The obvious solution to receiving calls to overridden methods would be:
1. Set their implementations as pointers to static methods
2. Create an instance variable in the ObjC object that would hold the pointer to its corresponding Java object
3. When a method is called, you'd get your Java `this` from that instance variable and forward the call to your Java object
But I can't seem to find any way whatsoever, at least one that doesn't feel extremely hacky and thus unreliable, to convert a Java object to a native pointer and back. This would also be useful, in some circumstances, for those C APIs that take a function pointer and `void*` as the "context" and then pass that `void*` back to your function. Or are there better solutions that don't need this?
More information about the panama-dev
mailing list