Objective-C binding pointer array to C#

709 Views Asked by At

I am trying to make a binding between an Objective-C library and C# within Xamarin. The class header that I am trying to bind is this:

@interface MGLPolyline : MGLMultiPoint <MGLOverlay>

+ (instancetype)polylineWithCoordinates:(CLLocationCoordinate2D *)coords
                              count:(NSUInteger)count;

What I can't figure is what to make the first parameter of the function. I have tried making the binding this:

Static][Export("polylineWithCoordinates:count:")]
    [Internal]
    MGLPolyLine PolyLineWithCoordinates(IntPtr coord, int count);



public partial class MGLPolyLine
{
    public static unsafe MGLPolyLine PolyLineWithCoordinates(CLLocationCoordinate2D[] coords) 
    {
        unsafe
        {
            GCHandle handle = GCHandle.Alloc(coords);
            IntPtr pointer = (IntPtr)handle;

            MGLPolyLine line = MGLPolyLine.PolyLineWithCoordinates(pointer,2);

            handle.Free();
            return line;
        }

    }
}

The code above always returns null from the MGLPolyLine.PolyLineWithCoordinates(pointer, 2) call, which leads me to believe that I'm not passing the array correctly. What is the correct way to do this binding?

Thanks

EDIT

I've used Objective-Sharpie to see what binding it would create for me and this is what I got:

// +(instancetype)polygonWithCoordinates:(CLLocationCoordinate2D *)coords count:(NSUInteger)count;
[Static]
[Export ("polygonWithCoordinates:count:")]
unsafe MGLPolygon PolygonWithCoordinates (CLLocationCoordinate2D* coords, nuint count);

The problem now is I get the error "btouch: Unknown kind CoreLocationCoordinate2D* coords in method 'MGLPolygon.PolygonWithCoordinates' (B1002)

1

There are 1 best solutions below

0
On BEST ANSWER

Turns out I was using GCHandle incorrectly. The working solution is:

   //ApiDefinition.cs
    [Static][Export ("polylineWithCoordinates:count:")][Internal]
 MGLPolyline PolylineWithCoordinates (IntPtr coords, nuint count);

// Extra.cs
public partial class MGLPolyline
{
    public static unsafe MGLPolyline PolylineWithCoordinates(CLLocationCoordinate2D[] coords)
    {
        MGLPolyline line = null;

        fixed(void* arrPtr = coords)
        {

            IntPtr ptr = new IntPtr(arrPtr);
            line = MGLPolyline.PolylineWithCoordinates(ptr, 2);   
        }

        return line;
    }
}