Jni4net,如何定义用于 Java 的 C# 事件

Jni4net, How to define C# events for use in Java

我正在测试如何使用 jni4net 库从 Java 代码订阅 C# 事件,但到目前为止,我制作的示例中有 none 已经运行。我正在尝试在引发事件时发送一组 Body() 对象。

C#代码:

public class LibEventHandler
{

    // Event for updating the body frame
    public delegate void UpdateBodyFrameEventHandler(object source, BodyDataEventArgs e);
    public event UpdateBodyFrameEventHandler UpdateBody;
    protected virtual void OnUpdateBody(BodyDataEventArgs bodies)
    {
        UpdateBodyFrameEventHandler handler = UpdateBody;
        if (handler != null)
           handler(this, bodies);
    }
    public void raiseUpdateBodyEvent(Body[] bodies)
    {
        OnUpdateBody(new BodyDataEventArgs() { Bodies = bodies });

    }

}

/// <summary>
/// A class extending EventArgs. Specifies the type Body[] as the event argument for the UpdateBody event
/// </summary>
public class BodyDataEventArgs : EventArgs
{
    public Body[] Bodies { get; set; }
}

Java代码:

public Start(){
    //initialise jni4net
    try {

        Bridge.setVerbose(true);
        Bridge.init();

        Bridge.LoadAndRegisterAssemblyFrom(new File("testlib.j4n.dll"));

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    //create a instance of the library's main class and get the object that has all the events
    LibMain lib = new LibMain();
    LibEventHandler evHandler = lib.getEventHandler();

    //subscribe to the event UpdateBody
    evHandler.addUpdateBody(new EventHandler(){
        @Override
        public void Invoke(system.Object sender, EventArgs e){
            Hello();
        }
    });
}


private void Hello(){
    System.out.println("Hello World! triggered by c# event");
}

java 端还没有使用 C# 事件给出的参数,但我只是想看看它是否会被触发。然而,这会引发以下异常:

    Exception in thread "main" System.ArgumentNullException: Value cannot be null.
Parameter name: method
   at System.Delegate.CreateDelegate(Type type, Object firstArgument, MethodInfo method, Boolean throwOnBindFailure)
   at System.Delegate.CreateDelegate(Type type, Object firstArgument, MethodInfo method)
   at net.sf.jni4net.utils.Convertor.StrongJ2CpDelegate[TRes](JNIEnv env, JniLocalHandle obj)
   at testlib.__LibEventHandler.UpdateBody0(IntPtr __envp, JniLocalHandle __obj, JniLocalHandle value)
    at testlib.LibEventHandler.addUpdateBody(Native Method)
    at testing.Start.<init>(Start.java:35)
    at testing.Testing.main(Testing.java:24)

另一个网站(下面的 link)讨论了相同的异常,但据我所知,我在定义我的事件时没有使用任何泛型。有谁知道我哪里出错了?

从 Java 到 DotNet

的异步回调的 MulticastDelegate

事实证明,JNI4NET 支持委托事件。所以解决方案是在 java 端使用带有监听器的接口事件系统。