Objective-C绑定指针数组到c#
本文关键字:数组 指针 绑定 Objective-C | 更新日期: 2023-09-27 18:10:14
我正在尝试在Xamarin中绑定Objective-C库和c#。我试图绑定的类头是这样的:
@interface MGLPolyline : MGLMultiPoint <MGLOverlay>
+ (instancetype)polylineWithCoordinates:(CLLocationCoordinate2D *)coords
count:(NSUInteger)count;
我不明白的是函数的第一个参数是什么。我试着让绑定如下:
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;
}
}
}
以上代码总是从MGLPolyLine返回null。PolyLineWithCoordinates(指针,2)调用,这使我相信我没有正确传递数组。做这个绑定的正确方法是什么?
感谢编辑
我用Objective-Sharpie来看看它会为我创建什么绑定,这是我得到的:
// +(instancetype)polygonWithCoordinates:(CLLocationCoordinate2D *)coords count:(NSUInteger)count;
[Static]
[Export ("polygonWithCoordinates:count:")]
unsafe MGLPolygon PolygonWithCoordinates (CLLocationCoordinate2D* coords, nuint count);
现在的问题是我得到错误"btouch: Unknown kind CoreLocationCoordinate2D* coordinates in method 'MGLPolygon。PolygonWithCoordinates"(B1002)
原来我使用GCHandle不正确。可行的解决方案是:
//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;
}
}