Getting a Java object from C++ back to C# to then pass to a Java API

We are currently writing a C++ native plug-in for Android that is to encode a video and audio stream using AMediaCodec. To feed the encoder, the media codec is used to create an input surface (AMediaCodec_createInputSurface) and from the ANativeWindow returned we can create a Java representation (ANativeWindow_toSurface). This returns a jobject. We pass this back to C# (at this stage as IntPtr) and need to pass it to a Java method (UnityPlayer.onDisplayChanged(int, Surface)).

I have found that it appears to be impossible to create a AndroidJavaObject instance from an existing Java object. I thought I may have to pass an AndroidJavaObject as the Surface parameter to the UnityPlayer.onDisplayChanged method, but AndroidJavaObject can only seem to create new instances of Java objects.

Has anyone done anything similar to this? I have spent several days searching for any tips on this, but it appears to be breaking new ground, which is never a fun thing in this mixed C#/C++/Java environment.

I believe the only way to pass things around between all three languages is to use low level functions from AndroidJNI class.

I ended up using JNI in C++ to pass the Surface object from C++ to a static field in the Java class (a UnityPlayerActivity derived class). All of this because the UnityPlayer instance is hidden within the UnityPlayerActivity class, and I need to call a method on the UnityPlayer instance with the Surface object.

But you’re in control of UnityPlayerActivity, can’t you change the code in UnityPlayerActivity to whatever you need?