Kotlin/ObjC - Creating MLMultiArrays and adding values

Hello all,

I’m trying to create an MLMultiArray in Kotlin and am having some trouble inserting values into my newly created MLMultiArray.

I have this function which takes in a 4-dimensional array and returns an MLMultiArray;

fun create(structure: List<List<List<List<Float32>>>>): MLMultiArray? {
            memScoped {
                val error = alloc<ObjCObjectVar<NSError?>>()

                val multiArray = MLMultiArray.create(
                    listOf(1, 320, 320, 3),
                    MLMultiArrayDataTypeFloat32,
                    error.ptr
                )

                for (batch in structure.indices) {
                    for (row in structure[batch].indices) {
                        for (column in structure[batch][row].indices) {
                            for (channel in structure[batch][row][column].indices) {
                                val key = listOf(NSNumber(batch), NSNumber(row), NSNumber(column), NSNumber(channel))
                                val value = structure[batch][row][column][channel]
                                val nNumber = NSNumber(value)

                                // does not compile :(
                                multiArray[key] = nNumber
                            }
                        }
                    }
                }

                return multiArray
            }
        }

I can’t figure out / find a method to insert the values into the MLMultiArray. In swift, I add the values in like above where key is of type [NSNumber]. Everything I’ve tried with memScoped and usePinned have been unsuccessful so far :frowning:

Any help or suggestions would be greatly appreciated!!!

Cheers

  • Callen E.

I was able to solve the answer by looking through the ObjC MLMultiArray documentation a little more closely!

First I used a pinned block for the looping:

multiArray.usePinned { array -> 
// for loop structure here
}

Then I used the instanced function array.get().setObject(NSNumber, [NSNumber])

Problem solved! my coreML model is now working properly :slight_smile: