cross platform - Callback/Delegate to Java for handling some C# event -
i using c# assembly in java application via jna & unmanaged exports. need implement callback/delegate in order inform java event in c# .dll has occured.
how can accomplished? or there reading reference suggest?
what tried far: using java native access (jna) & unmanaged exports robert giesecke in order call c# methods java. - works fine far.
i pass callback-method as void* pointer java c#. call method somehow.
for verification added code use:
defining jna interface (incl. callback) in java:
import com.sun.jna.callback; import com.sun.jna.library; public interface ijna extends library { interface sig_t extends callback { boolean invoke(int signal); } string testcallback(sig_t callbackparam); }
unsage c# method exported unmanaged code, receiving "any pointer" (void*) parameter should adress of method
[dllexport] public unsafe static string testcallback(void* somemethod) { //use somemethod here if(somemethod != null) return "not null"; // somemethod not null when running app else return "null"; }
load .dll, define callback function , call in java.
public static void main(string[] args) { //load unmanaged .dll ijna.sig_t referencetofunction = new ijna.sig_t() { @override public boolean invoke(int sig) { system.out.println("signal " + sig + " raised"); return true; } }; string test = instance.testcallback(referencetofunction);//returns "not null" system.out.println(test); }
i solve it. using marshal.getdelegateforfunctionpointer(intptr, type) possible convert void* (any pointer) c# delegate.
so c# code adapted following:
delegate void del(int someint); del csharpfuncptr; //save delegate, not void* (the void* not preventing gb deleting method, , therefore invalid) [dllexport] public unsafe static string testcallback(void* somemethod) { intptr method = new intptr(somemethod); csharpfuncptr = (del)marshal.getdelegateforfunctionpointer(method, typeof(del)); csharpfuncptr(5); }
Comments
Post a Comment