简体   繁体   English

Java是否可以接收和调用从另一种语言接收的静态方法的委托?

[英]Can Java receive and invoke a delegate of static method received from another language?

For example, in C# I have 例如,在C#中

[MonoPInvokeCallback(typeof(PointDelegate))]
public static void Callback(int x, int y)
{ .... }

This method is stored in a delegate of signature return void (int, int). 此方法存储在签名返回void(int,int)的委托中。

public delegate void PointDelegate(int x, int y);

I sent this delegate variable to Objective-C and over there I was able to call it directly to invoke Callback() . 我将此委托变量发送到Objective-C,在那儿我可以直接调用它以调用Callback() It just works. 它只是工作。 (I have declared the equivalent typedef at Objective-C side to match) (我已经在Objective-C端声明了等效的typedef进行匹配)

C# C#

objC(Callback);

Objective-C 目标C

typedef void (*PointDelegate)(int x, int y);
void objC(PointDelegate delegateFromCSharp)
{
   delegateFromCSharp(1,2);
}

What is the equivalent in Java? Java中的等效功能是什么? Assuming I can call a method in Java already and the delegate is being passed as the only parameter, what would be the signature of that Java method? 假设我已经可以用Java调用方法,并且将委托作为唯一参数传递,那么该Java方法的签名是什么? And how to invoke the received delegate? 以及如何调用接收到的委托?

I managed to get it working. 我设法使它起作用。 This solution uses Unity's "AndroidJavaProxy" class so I am not sure what it will be using pure JNI. 该解决方案使用Unity的“ AndroidJavaProxy”类,因此我不确定它将使用纯JNI。 But I am glad it works for my case. 但我很高兴它对我的情况有用。

This is C# : 这是C#:

public class IntInterface : AndroidJavaProxy
{
    public IntInterface() : base("com.YourCompany.YourApp.YourClass$IntInterface") { }
    void Call(int i)
    {
        Debug.Log("Java says : " + i);
    }
}

Then I call static method on Java with new IntInterface() as a parameter. 然后,我使用new IntInterface()作为参数在Java上调用静态方法。

At Java side I have a matching interface waiting. 在Java端,我有一个匹配的接口在等待。 It can accept IntInterface from C# side without throwing JNI : unknown signature for type anymore. 它可以从C#端接受IntInterface ,而不会抛出JNI : unknown signature for type The Call is also being matched with C# ones. Call也与C#匹配。

    public static void StaticMethod(IntInterface intInterface) {
        intInterface.Call(555);
    }

    @FunctionalInterface
    public static interface IntInterface{
        void Call(int i);
    }

The result is "Java says : 555" I just invoked C# method Call(int i) with parameter from Java. 结果是"Java says : 555"我刚刚使用Java参数调用了C#方法Call(int i)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM