1

For example, in C# I have

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

This method is stored in a delegate of signature return 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(). It just works. (I have declared the equivalent typedef at Objective-C side to match)

C#

objC(Callback);

Objective-C

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

What is the equivalent in 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? And how to invoke the received delegate?

5argon
  • 3,683
  • 3
  • 31
  • 57
  • 1
    Its called native. Look at implementation of Thread for example http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/Thread.java – Noixes Nov 03 '17 at 08:05
  • 1
    Java has no concept of delegates, you can use functional interfaces & method references (see https://stackoverflow.com/questions/39346343/java-equivalent-of-c-sharp-delegates-queues-methods-of-various-classes-to-be-ex). – Tetsuya Yamamoto Nov 03 '17 at 08:06

1 Answers1

1

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. But I am glad it works for my case.

This is 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.

At Java side I have a matching interface waiting. It can accept IntInterface from C# side without throwing JNI : unknown signature for type anymore. The Call is also being matched with C# ones.

    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.

5argon
  • 3,683
  • 3
  • 31
  • 57