JNBridge Logo

Callbacks (part 3)

Monday, Sep. 18th 2006

In the third part of our series on callbacks, we’ll discuss what to do if we have a .NET assembly that implements callbacks using a Java-style listener interface.  Since JNBridgePro only supports the delegate/event callback style in Java-to-.NET projects, we need to have a way to convert between the two styles.  Here’s one such way.  Assume we have the following listener interface:

public interface MyCallbackInterface
{ 
    bool myCallbackMethod(int param1, string param2);  

}
 
and the following callback generator class public class CallbackGenerator
{
 
    public static void registerCallback(MyCallbackInterface theCallback) {…}  

    public static void fire() {…}
}
 
We can create .NET event-style wrappers that can be proxied as follows:
public delegate bool MyCallbackHandler(int param1, string param2);  

public class NewCallbackGenerator
{
    // this is the wrapper to convert listeners to events
 

    private class MyCallbackHandlerWrapper : MyCallbackInterface
    {
        MyCallbackHandler mch;
        public MyCallbackHandlerWrapper(MyCallbackHandler mch)
        {
            this.mch = mch;
        }
  
        public bool myCallbackMethod(int param1, string param2) 
        {   

            return mch(param1, param2);
        }
    }
  
    // here is the event interface 
    public static event MyCallbackHandler MyEvent 
    {  

        add
        {
            MyCallbackHandlerWrapper mcw = new MyCallbackHandlerWrapper(value);
            CallbackGenerator.registerCallback(mcw);
        }
    }
  
    public static void fireEvents() 
    {   

        CallbackGenerator.fire();
    }
}
 
You should proxy and use MyCallbackHandler and NewCallbackGenerator as you would any other proxied delegate/event-style callback.

 

 

 

 

 

 

 

 

 

 

 

Bookmark and Share
Posted by JNBridge | in Tips and examples | Comments Off

Comments are closed.