您的位置:首页 > 移动开发 > Objective-C

Xamarin.iOS使用Objective-C静态类库.a(Linking Native Libraries)

2014-11-03 16:44 405 查看
Xamarin静态类库的binding实际上是一个C#与Objective-C方法间映射过程,由于第三方SDK对iOS开发至关重要,因此官方文档中也对这块也做了完整的介绍(Binding
Objective-C Libraries),但对于一个完全入门级的程序员来说,这块还是有诸多麻烦,并且部分Api类型文档上也未曾提到。下面将以百度地图作为案例,全面解析静态类库binding工程的知识与问题(Mac OS 10.8.4及以上系统)。生成dll过程:



在开始之前需要了解几个iOS原生开发中的基础知识:

1.Command Line Tools for Xcode(XCode命令行工具)

里面包含了一些常用的命令,在处理静态类库时经常用到,有两种安装方法:

1)是在Xcode设置>>Downloads更新安装;

2)使用Mac os下“终端”中敲入命令 xcode-select --install 安装即可。



2.静态类库(.a)编译类型

由于iOS编译机制上的区分,静态类库分为模拟器(i386),真机(ARMv7/ARMv7s/ARMv64等),这是由设备CPU决定的。一般厂商提供的静态类库都会分别提供(例如BaiduMap:Release-iphoneos(真机)/Release-iphonesimulator(模拟器)),那在没有明确标识的情况下,我们怎么区分这些静态类库是真机还是模拟器呢?简单直观的查看方法,打开Xamarin Studio,新建BindingProject,然后将[libBaidu.a]添加到工程上,打开自动生成的linkwith.cs文件就可以查看到静态类库的类型【可参考Monotouch
BindingProject之友盟SDK】。



3.真机模拟器通用静态类库.a生成

为什么要使用这种通用类库?方便你模拟器真机调试。由于通用包比原来增加接近一倍,因此发布的时候记得只使用真机包,以减少.ipa的大小。操作方法

1)在桌面新建文件夹[BaiduLib],打开终端,输入命令cd,并且拖动[BaiduLib]到终端命令后面,按回车(意在将文件默认保存在此文件夹下)。

2)接着输入命令lipo -create [libbaidumapapi.a] [libbaidumapapi.a] -output libBaiduSDK.a,(其中[libbaidumapapi.a] [libbaidumapapi.a]只要拖动到终端框内即可)敲回车,稍等片刻就可以在文件夹[BaiduLib]下看到[libBaiduSDK.a],将其添加到Binding工程中就可以查看到三种类型都存在:LinkTarget.Simulator
| LinkTarget.ArmV7 | LinkTarget.ArmV7s







4.Framework系统框架引用

几乎每个静态类库的实现都引用了或多或少的系统framework,规范的静态类库引用都会提醒你使用了哪些系统framework,而在xcode中添加是件简单的事,但在xamarin studio中地却要使用gcc命令来添加。文档中有介绍:【Linking
Your Library】

注意几个关键字:

1)-gcc_flags,普通native library编译

2)-cxx,包含C++代码类型编译

3)-L${ProjectDir},当前文件目录

4)-framework,框架类型,例如:[-framework CFNetwork]

5)--registrar:legacy,引用文档解释:The new registrars
(first introduced in 6.2.6) are now enabled by default. They catch many more errors and will prevent many bugs or undefined runtime behaviors. It is possible to fallback to the previous registrars by using --registrar:legacy as an additional mtouch argument。简单来说应该是编译器版本问题的一个控制开关;

6)-ObjC,一般放命令行尾部,需要时添加

完整的命令,以百度地图为例:

[csharp] view
plaincopy

--registrar:legacy -cxx -gcc_flags "-L${ProjectDir} -framework MapKit -framework CoreLocation -framework QuartzCore -framework OpenGLES -framework SystemConfiguration -framework CoreGraphics -framework Security -ObjC"

命令添加在UI工程中,工程选项>>iOS Build>>Additional Options>>Additional mtouch arguments


5.C#与ObjC数据类型



了解完Xamarin.iOS的基础所需,正式开始接下来繁多无味而重要的映射方法binding工作,当然xamarin官方也提供了一个自动生成工具,但这个工具给我感觉不太能用,也许没深入研究吧,感兴趣的朋友可以下载试用一下【objective_sharpie】(如果你还无法开始时,建议参考【友盟SDK的调用】)。

开始之前简单介绍一下:

一个头文件中可以出现多个@interface,每个@interface在C#中都是一个类,例如:BMKActionPaopaoView.h文件:

[objc] view
plaincopy

@interface BMKActionPaopaoView : UIView

- (id)initWithCustomView:(UIView*)customView;

@end

[csharp] view
plaincopy

//BMKActionPaopaoView.h

[BaseType (typeof(UIView))]

interface BMKActionPaopaoView

{

/// <summary>

/// [构造函数模式]

/// 初始化并返回一个BMKActionPaopaoView

/// - (id)initWithCustomView:(UIView*)customView;

/// </summary>

/// <param name="customView">Custom view.</param>

[Export ("initWithCustomView:")]

IntPtr Constructor (UIView customView);

}



1.打开StructsAndEnums.cs文件,如其名字一样这里是编写结构体和枚举的,也是最简单的一块:

1)枚举(Enums)

打开头文件[BMKAnnotationView.h],可以看到原生代码:

[objc] view
plaincopy

enum {

BMKAnnotationViewDragStateNone = 0, ///< 静止状态.

BMKAnnotationViewDragStateStarting, ///< 开始拖动

BMKAnnotationViewDragStateDragging, ///< 拖动中

BMKAnnotationViewDragStateCanceling, ///< 取消拖动

BMKAnnotationViewDragStateEnding ///< 拖动结束

};

typedef NSUInteger BMKAnnotationViewDragState;

[csharp] view
plaincopy

public enum BMKAnnotationViewDragState

{

None = 0, ///< 静止状态.

Starting, ///< 开始拖动

Dragging, ///< 拖动中

Canceling, ///< 取消拖动

Ending ///< 拖动结束

}

简单的把有含义的单词提取出来,以方便在C#中使用,枚举无非就是使用整数0、1、2代表各实际含意。

2)结构体(Structs)

打开头文件[BMKType.h],可以看到原生代码:

[objc] view
plaincopy

typedef struct {

CLLocationCoordinate2D center; ///< 中心点经纬度坐标

BMKCoordinateSpan span; ///< 经纬度范围

} BMKCoordinateRegion;

[csharp] view
plaincopy

public struct BMKCoordinateSpan

{

public double latitudeDelta;

public double longitudeDelta;

}

2.Binding APIs

打开ApiDefinition.cs,以下将开始对头文件中出现的原生语法类型进行介绍

1)Binding Methods(基础方法)

[objc] view
plaincopy

- (void)setCoordinate:(CLLocationCoordinate2D)newCoordinate;

+ (BMKArcline *)arclineWithPoints:(BMKMapPoint *)points;

+ (BMKCircle *)circleWithCenterCoordinate:(CLLocationCoordinate2D)coord radius:(CLLocationDistance)radius;

C#代码,“+”代表静态方法,加Statice标识;当遇到不是基本数据类型时,例如[BMKCircle],可找着对应头文件,先进行其对象binding

[csharp] view
plaincopy

[Export ("setCoordinate:")]

void SetCoordinate (CLLocationCoordinate2D newCoordinate);

[Static,Export ("arclineWithPoints:")]

BMKArcline ArclineWithPoints (BMKMapPoint points);

[Static,Export ("circleWithCenterCoordinate:radius:")]

BMKCircle CircleWithCenterCoordinate (CLLocationCoordinate2D coord, double radius);

带out/ref parameters的方法

[objc] view
plaincopy

- (void) someting:(int) foo withError:(NSError **) retError;

- (void) someString:(NSObject **)byref;

[csharp] view
plaincopy

[Export ("something:withError:")]

void Something (int foo, out NSError error);

[Export ("someString:")]

void SomeString (ref NSObject byref);

2)Binding Properties(属性)

[objc] view
plaincopy

@property (nonatomic) CGPoint calloutOffset;

@property (nonatomic, getter=isSelected) BOOL selected;

@property (nonatomic, getter=isDraggable) BOOL draggable __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_3_2);

@property (nonatomic, retain) NSArray *POIs;

C#代码,相关对应[Memory management attributes内存管理标识]ArgumentSemantic标识有三个:Assign,Copy,Retain,依情况而定;与静态方法同样如果是带“+”,也要进行[Static]标识

[csharp] view
plaincopy

[Export ("calloutOffset")]

PointF CalloutOffset{ get; set; }

[Export ("selected")]

bool Selected{ [Bind ("isSelected")]get; set; }

[Export ("draggable")]

bool Draggable{ [Bind ("isDraggable")]get; set; }

[Export ("POIs", ArgumentSemantic.Retain)]

NSArray POIs{ get; set; }

3)Binding Constructors(构造函数)

[objc] view
plaincopy

- (id)initWithCustomView:(UIView*)customView;

C#对应,id可以理解为一个实例化对象

[csharp] view
plaincopy

[Export ("initWithCustomView:")]

IntPtr Constructor (UIView customView);

4)Binding Protocols(委托协议)

Protocol需要在interface对应头上添加[Model][Protocol],以标明为Delegate

[objc] view
plaincopy

@protocol BMKLocationServiceDelegate <NSObject>

@optional

- (void)willStartLocatingUser;

- (void)didStopLocatingUser;

@end

C#对应,@optional可选标识不用标识

[csharp] view
plaincopy

[Model][Protocol]

[BaseType (typeof(NSObject))]

interface BMKLocationServiceDelegate

{

[Export ("willStartLocatingUser")]

void willStartLocatingUser ();

[Export ("didStopLocatingUser")]

void didStopLocatingUser ();



而需要使用委托协议方法的对应类中,需要这样实现

[objc] view
plaincopy

@property (nonatomic, assign) id<BMKLocationServiceDelegate> delegate;

C#对应,Assign与属性标识一致,根据实际添加

[csharp] view
plaincopy

[Export ("delegate", ArgumentSemantic.Assign)]

NSObject WeakDelegate { get; set; }

[Wrap ("WeakDelegate")]

BMKLocationServiceDelegate Delegate { get; set; }

5)Binding Class Extensions

还未使用过:

[csharp] view
plaincopy

[BaseType (typeof (UIResponder))]

interface UIView {

[Bind ("drawAtPoint:withFont:")]

SizeF DrawString ([Target] string str, PointF point, UIFont font);

}

6)Binding Objective-C Argument Lists

[objc] view
plaincopy

- (void) appendWorkers:(XWorker *) firstWorker, ... NS_REQUIRES_NIL_TERMINATION ;

[csharp] view
plaincopy

[Export ("appendWorkers"), Internal]

void AppendWorkers (Worker firstWorker, IntPtr workersPtr)

7)Binding Fields

Sometimes you will want to access public fields that were declared in a library.

还未使用过:

[csharp] view
plaincopy

[Field ("NSSomeEventNotification")]

NSString NSSomeEventNotification { get; }

8)Binding Notifications(通知)

还未使用过:

[csharp] view
plaincopy

interface MyClass {

[Notification]

[Field ("MyClassDidStartNotification")]

NSString DidStartNotification { get; }

}

9)Binding Categories(类别)

这个百度地图上出现比较多,还有几个问题官网没提到的问题:

[objc] view
plaincopy

@interface BMKMapView (LocationViewAPI)

/// 问题出现在此

@property (nonatomic) BOOL showsUserLocation;

-(void)updateLocationData:(BMKUserLocation*)userLocation;

@end

[Category]标识声明;文档中只提到了对方法的解析,但没有对属性进行说明,如果就按之前对属性进行解析,编译时会报错cannot
declare instance members in a static class(不能在静态类中声明实例成员),语法上的错误,根据要对其进行改造,利用ObjC上get,set构造器的规则进行赋取值修改,这时showsUserLocation就可以用了

[csharp] view
plaincopy

[Category,BaseType (typeof(BMKMapView))]

public partial interface LocationViewAPI

{

[Export ("setShowsUserLocation:")]

void SetShowsUserLocation(bool isShow);

[Export ("updateLocationData:")]

void UpdateLocationData (BMKUserLocation userLocation);



10)Binding Blocks(可理解为Action)

ObjC是为了避免Protocol的混乱而设计的

[objc] view
plaincopy

- (void) enumerateObjectsUsingBlock:(void (^)(id obj, BOOLBOOL *stop) block

[csharp] view
plaincopy

delegate void NSSetEnumerator (NSObject obj, ref bool stop)

[Export ("enumerateObjectUsingBlock:")]

void Enumerate (NSSetEnumerator enum)

11)Asynchronous Methods(异步方法)

这个api中也比较少见

[csharp] view
plaincopy

[Export ("loadfile:completed:")]

[Async]

void LoadFile (string file, Action<string> completed);

12)Binging [typedef]

使用typedef为现有类型创建同义字,定义易于记忆的类型名

[objc] view
plaincopy

typedef void(^ESTCompletionBlock)(NSError* error);

typedef void(^ESTUnsignedCompletionBlock)(unsigned value, NSError* error);

typedef void(^ESTBoolCompletionBlock)(BOOL value, NSError* error);

typedef void(^ESTStringCompletionBlock)(NSString* value, NSError* error);

[csharp] view
plaincopy

public delegate void ESTCompletionBlock(NSError error);

public delegate void ESTUnsignedCompletionBlock(byte value, NSError error);

public delegate void ESTBoolCompletionBlock(bool value, NSError error);

public delegate void ESTStringCompletionBlock(NSString value, NSError error);

3.备注

1)NSArray数组

由于ObjC中直接以NSObjce进行操作,因此有些时候并不知道NSArray的对象到底是何种数据类型,但如果在解析过程中,你很明确知道时,可以这样解析

[objc] view
plaincopy

- (NSArray *)getPeerViews ();

- (void) setViews:(NSArray *) views

[csharp] view
plaincopy

[Export ("getPeerViews")]

UIView [] GetPeerViews ();

[Export ("setViews:")]

void SetViews (UIView [] views);

2)NSString类型,可以直接使用string替换

3)委托协议的使用

[objc] view
plaincopy

@interface Demo : NSObject <UIAlertViewDelegate>

@end

[csharp] view
plaincopy

[BaseType (typeof (NSObject), KeepUntilRef="Dismiss"),

Delegates=new string [] { "WeakDelegate" }, Events=new Type [] { typeof (SomeDelegate) }) ]

class Demo {

[Export ("show")]

void Show (string message);

}

4)public partial的使用

在Binding Categories(类别)中,必须使用public partial [interface LocationViewAPI]标识,否则就无法成功调用。

参考链接:http://ipixels.net/blog/specify-extra-gcc-flags-for-native-library-binding-in-xamarin-ios/

http://www.aaronheise.com/2013/08/gooddynamicsmonotouch/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: