简体   繁体   中英

how to pass a list to a binding in xamarin

I'm did a JNI binding in Xamarin for an Android project I'm working on. The original Java function of interest accepted an empty ArrayList<String> as one of the input parameters and added contents to the list as part of the function (modifying the object itself).

When converted to C# code, the input type of the list was changed to:

global::System.Collections.Generic.IList<string>. 

The return value of the function remains the same, but the input list is no longer being modified. I think this has something to do with the way that the binding is handling the marshalling of the function parameters.

Is there something I should be doing to modify the binding in order to modify the input parameter (p2 in generated C# code shown below)?

public static unsafe int ProcessAudioBuffer (short[] p0, int p1, global::System.Collections.Generic.IList<string> p2)
        {
            if (id_processAudioBuffer_arraySILjava_util_List_ == IntPtr.Zero)
                id_processAudioBuffer_arraySILjava_util_List_ = JNIEnv.GetStaticMethodID (class_ref, "processAudioBuffer", "([SILjava/util/List;)I");
            IntPtr native_p0 = JNIEnv.NewArray (p0);
            IntPtr native_p2 = global::Android.Runtime.JavaList<string>.ToLocalJniHandle (p2);

            try {
                JValue* __args = stackalloc JValue [3];
                __args [0] = new JValue (native_p0);
                __args [1] = new JValue (p1);
                __args [2] = new JValue (native_p2);
                int __ret = JNIEnv.CallStaticIntMethod  (class_ref, id_processAudioBuffer_arraySILjava_util_List_, __args);
                return __ret;
            } finally {
                if (p0 != null) {
                    JNIEnv.CopyArray (native_p0, p0);
                    JNIEnv.DeleteLocalRef (native_p0);
                }
                JNIEnv.DeleteLocalRef (native_p2);
            }
        }

Pass in a Android.Runtime.JavaList<string> where your function expects a System.Collections.Generic.IList<string> . Android.Runtime.JavaList<T> implements .NET's System.Collections.Generic.IList<string> interface.

The official Xamarin documentation for JavaList<T> states the following.

ArrayList is an implementation of IList , backed by an array. [...] This class is a good choice as your default List implementation.

I suspect that the issue with using a pure .NET type such as List<T> is that it does not inherit from Java.Lang.Object and, therefore, there is no Java counterpart to modify. Hence, you do not see the modification reflected after you call the function.

I had a similar issue when using an OpenCV binding in Xamarin and passing in a Android.Runtime.JavaList<T> resolved the issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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