Unity 通过JNI传递数组到Android

Unity 通过JNI传递数组到Android

  • 项目中有一个需求就是获得Unity端的某个物体的位置,然后传递给Android端.
  • 需要借助 JNI

Unity端代码:

public class TestArrayThroughJNI
{
    private static AndroidJavaObject _plugin;

    static GPlayIABPlugin()
    {
        if( Application.platform != RuntimePlatform.Android )
            return;

        //This is apparently good practice, but seems to have no effect anyways!
        AndroidJNI.AttachCurrentThread();

        // find the plugin instance
        using (var pluginClass = new AndroidJavaClass("com.company.myplugin"))
            _plugin = pluginClass.CallStatic<AndroidJavaObject>( "instance" );
    }
    public static void PassArrayToJava()
    {
        float[] testFltArray = {1.5f, 2.5f, 3.5f, 3.6f};

        IntPtr jAryPtr = AndroidJNIHelper.ConvertToJNIArray(testFltArray);
        jvalue[] blah = new jvalue[1];
        blah[0].l = jAryPtr;

        IntPtr methodId = AndroidJNIHelper.GetMethodID(_plugin.GetRawClass(), "testArrayFunction");
        AndroidJNI.CallVoidMethod(_plugin.GetRawObject(), methodId, blah);
    }
}

Android端代码:

public class JavaTestArray
{
    //Used by Unity to grab the instance of this Java class.
    private static IABUnityPlugin _instance;

    //Magic happens here.
    public void testArrayFunction(float[] test)
    {
        Log.i("Unity", "Float[]: " + test + " and length: " + test.length);

        for(int i = 0; i < test.length; i++)
        {
            Log.i("Unity", "[" + i + "] " + test[i]);
        }
    }

    public static JavaTestArray instance()
    {
        if(_instance == null)
            _instance = new JavaTestArray();

        return _instance;
    }
}

结果:

Output:
Float[]: [F@405608d0 and length: 4
[0] 1.5
[1] 2.5
[2] 3.5
[3] 3.6

参考文献

Passing arrays through the JNI

猜你喜欢

转载自blog.csdn.net/qjh5606/article/details/85298981