UnitySendMessage from a C extension for Android is not working

Hi, I’m trying to implement callbacks from a native extension to C# by using UnitySendMessage.

Here’s how I try to send the message:

  void SendMessage(const char *object, const char *method, const char *parameter)
  {
     jclass UnityPlayer = jni_env->FindClass("com/unity3d/player/UnityPlayer");
     jmethodID UnitySendMessage = jni_env->GetStaticMethodID(UnityPlayer, "UnitySendMessage", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V");
     LOGI("Sending message with UnityPlayer=%x and UnitySendMessage=%x", UnityPlayer, UnitySendMessage);
     jthrowable exception = jni_env->ExceptionOccurred();

     if (exception) {
       LOGI("Unable to initialize UnitySendMessage");
       jni_env->ExceptionDescribe();
       jni_env->DeleteLocalRef(exception);
       jni_env->ExceptionClear();
     }

     jstring objectStr = jni_env->NewStringUTF(object);
     jstring methodStr = jni_env->NewStringUTF(method);
     jstring parameterStr = jni_env->NewStringUTF(parameter);

     jni_env->CallStaticVoidMethod(UnityPlayer, UnitySendMessage, objectStr, methodStr, parameterStr);

     exception = jni_env->ExceptionOccurred();
     if (exception) {
       LOGI("Unable to call UnitySendMessage for: %s - %s - %s", object, method, parameter);
       jni_env->ExceptionDescribe();
       jni_env->DeleteLocalRef(exception);
       jni_env->ExceptionClear();
     } else {
       LOGI("Called UnitySendMessage for: %s - %s - %s", object, method, parameter);
     }
  }

I use it like this:

 SendMessage("MyObject", "Callback", "some stringgg");

And here’s the C# class:

using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;
using System;

public class MyObject : MonoBehaviour {
  public void Callback(string message)
  {
    Debug.Log("Callback! "+ message);
  }
}

But the Callback method is never called. Any ideas?

The issue was that I had to create a GameObject and attach the behaviour to it, otherwise there was no way to actually reference it by name.