Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to use arrays in MonoMac

I'm just started working on a project in MonoMac, which is pretty cool so far. But there're still some things I'm not sure of. For example: How do you use arrays? Here's what I found out: When I get an NSArray back from a method I'm calling and I try to get one of the custom objects in that array I keep getting something like "cannot convert type System.IntPtr to MyType".

NSArray groupArray = (NSArray)groupDictionary.ObjectForKey(key);
MyType myObject = (MyType)groupArray.ValueAt(0);

That's for arrays I get back. But what if I want to create an array on my own? The implementation of NSArray does not allow me to instantiate it. So if I got the MonoMac website right, I should use an ordinary array like this

int[] intArray = int[10];

respectively an strongly-typed array which I'm not aware of how to use it in C#.

So what's the way to go here?

Thanks
–f

like image 837
flohei Avatar asked Nov 06 '10 14:11

flohei


1 Answers

In general, using NSArray is not very useful, because you end up with the problems that you described above.

This is why in general you should convert the NSArray into a strongly typed array. The MonoMac low-level runtime does this for all callbacks already on your behalf.

Usually you would do this:

YourType [] stronglyTyped = NSArray.ArrayFromHandle<YourType> (arrayIntPtrHandle);

Note that NSArray can only store NSObjects, so "YourType" needs to be an object derived from NSObject.

Now, if you still want to use the NSArray, what you need to remember is that the ValueAt returns the underlying object handle (the IntPtr), to use this with C# you need to convert this into an NSObject. You do this with the Runtime.GetNSObject method, you can cast the result to the most derived type:

YourType x = (YourType) Runtime.GetNSObject (NSArray.ValueAt (0));

That being said, if you are using the API binding tools to access an Objective-C API, you are not binding things correctly. Your contract API should instead of having an NSArray should have the strongly typed version, so:

 [Export ("getElements")]
 NSArray GetElements ();

Should become:

 [Export ("getElements")]
 YourType [] GetElements ();
like image 81
miguel.de.icaza Avatar answered Sep 22 '22 00:09

miguel.de.icaza