SlideShare uma empresa Scribd logo
1 de 48
MonoTouch/iOS Native Interop
Xamarin Inc
Agenda
• When to Bind
• How to bind
• Improving the binding
INTRODUCTION TO BINDINGS
Xamarin.iOS Native Interop
• Consume Objective-C or C code
– Integrated existing code
– Move performance sensitive code to C/assembly
– Adopt third party libraries
– Adopt third party controls/frameworks
• At the core of Xamarin.iOS itself
Integration with Native Libraries
• iOS Native Libraries
– Core libraries written in C
– High-level libraries written in Objective-C
• Consuming C Libraries:
– Uses standard .NET Platform/Invoke support
• Consuming Objective-C Libraries:
– Binding Projects
– “Projects” Objective-C to C#
– Provides full integration with native object hierarchy
Mono/Objective-C Bindings
• Used by MonoTouch itself
– Every Objective-C API is surfaced this way.
• Tool produces C# libraries that:
– Map 1:1 to underlying Objective-C libraries
– Allow instantiating Objective-C classes
– Allow subclassing/overwriting of behavior
– Can extend Objective-C with C# idioms
Configuring Objective Sharpie
Header Files + Namespace
Generating the IDL
MonoTouch Binding Project
Creating a Binding
• Enumerations and Structures
– Contain core definitions used by the interface
• C# Interface Definition
– Defines how to project Objective-C to C#
– Name mapping, Overloads
• Curated Extensions:
– Contains helper features to simplify development
– Add strongly-typed features
Example: C# Interface Definition
Objective-C
@interface MagicBeans : NSObject {
// …
}
-(id) initWithString:(NSString*)msg;
+(NSArray*) getAllBeans();
-(void) grow;
-(void) harvest:(NSDate *) time;
@end
Example: C# Interface Definition
Objective-C
@interface MagicBeans : NSObject {
// …
}
-(id) initWithString:(NSString*)msg;
+(NSArray*) getAllBeans();
-(void) grow;
-(void) harvest: (NSDate *) time;
@end
C# Interface Definition
[BaseType (typeof (NSObject))]
Interface MagicBean {
[Export (“initWithString:”)]
IntPtr Constructor (string msg);
[Static, Export (“getAllBeans”)]
MagicBeans [] GetAllBeans ();
[Export (“grow”)]
void Grow ();
[Export (“harvest:”)]
void Harvest (NSDate time);
}
Binding “MagicBeans” library
MagicBeans.dll
Enumerations,
Structures
C# Interface
Definition
Curated
Extensions
libMagicBeans.a
C# Source Native Binary .NET Binary
Single deployment unit
Contains:
• C# binding
• Native Library
• Assets (artwork,
audio)
OBJECTIVE SHARPIE
Compiler Driven Bindings
• ObjectiveSharpie Tool
– Uses LLVM’s Objective-C compiler to parse API
– Applies standard Binding rules
– Generates Baseline C# IDL for you
– Then you modify
• Available Today
– http://bit.ly/objective-sharpie
BASICS OF BINDINGS
Basics of Bindings
• Binding Classes
• Binding Protocols
• Methods, Properties
– Type mappings
– Arrays
– Strings
• Delegate classes (and Events)
• Exposing Weak and Strong Types
• Binding Blocks
Class Declarations
Objective-C C# Mapping Result
Class
Declarati
on
@interface Foo : Bar [BaseType (typeof (Bar))]
interfaceFoo
C# class
Class
adopting
protocol
@interface Foo : Bar
<Pro>
[BaseType (typeof (Bar))]
interfaceFoo : Pro
C# class, inlined
protocol methods
Protocol @protocol Foo <Bar> [BaseType (typeof (Bar))]
[Model]
interface Foo
C# class with methods
to override
Category @interface
Foo(Cute)
[BaseType (typeof (Foo))]
interface Cute
C# extensions method
class
Objective-C Method Selectors
-(float) getNumber;
• Meaning:
– “-” means it is an instance method
– Float return type
– Selector name is “getNumber”
• C# IDL:
*Export (“getNumber”)+
float GetNumber ();
Objective-C Method Selectors
+(float) add:(int) first and:(int) second;
• Meaning:
– “+” means it is a static method
– Float return type
– Takes two int arguments
– Selector name is “add:and:”
• C# IDL:
*Export (“add:and:”)+
float Add (int first, int second)
Objective-C Property Selectors
@property (readwrite) int foo;
• Meaning:
– Property is read/write
– int return type
– Selector pair is: “foo” (get) and “setFoo:” (set)
• C# IDL:
*Export (“foo”)+
int Foo { get; set; }
Binding Correctness
• [Export] definitions might have errors
– Transcription errors
– Accidental setters, or wrong getters
• Create a unit test
– Subclass ApiCtorInitTest
Testing your APIs
[TestFixture]
public class BindingCtorTest : ApiCtorInitTest {
protected override Assembly Assembly {
get {
return typeof (CCAccelAmplitude).Assembly; }
}
}
}
Core Type Mappings
Objective-C C#
BOOL, GLBoolean bool
NSString * C# string or NSString
char * [PlainString] string
NSInteger, NSUInteger int, uint
CGRect, CGPoint, CGSize RectangleF, PointF, SizeF
id NSObject
SEL ObjCRuntime.Selector
dispatch_queue_t CoreFoundation.DispatchQueue
CGFloat, GLFloat float
Arrays
• NSArray represents arrays
– Untyped, no code completion
• When binding, use strong types instead
– “NSArray” becomes “UIView *+”
– Requires a trip to the documentation
LINKING LIBRARIES
Linking Libraries
• Use assembly-level attribute LinkWith
– [assembly:LinkWith (…)
• Specify static and dynamic dependencies
– Frameworks (for required dependencies)
– WeakFrameworks (for optional dependencies)
– Pass system linker flags
• Libraries referenced are bundled into DLL
– Simplifies distribution (single DLL contains all resources)
– Unpacked before the final build
Native Libraries
• FAT libraries
– One libFoo.a may contain x86, arm, thumb code
– Not all libraries build have all targets
– Make sure you build all the supported targets
– See monotouch-bindings’ Makefile for samples
• IDE automatically examines fat libraries
– And produces the proper LinkWith attribute
New: SmartLink
• By default, all native code is linked-in
• SmartLink merges Mono and System linker
– Only code that is directly referenced is included
– Caveat: dynamic Objective-C code can fail
– Big savings
SmartLink effect on Samples
-
2,000
4,000
6,000
All code
Smart Linking
Size Savings
0
100,000
200,000
300,000
400,000
500,000
Savings
ADVANCED BINDING FEATURES
Binding Public Variables
• Mapped to properties in C#
• Use the Field attribute.
• Provide get or get/set
[Field (“FooServiceKey”, “__Internal”)]
NSString ServiceKey { get; set; }
• Use “__Internal” for binding libraries
• Supports NSArray, NSString, int, long, float, double, IntPtr and
System.Drawing.SizeF
Notifications
• Basic API:
– NSNotificationCenter takes a string + method
– Invokes method when notification is posted
– Contains an NSDictionary with notification data
• We want a strongly typed API:
– Simplify discovery of available notifications
– Simplify discovery of parameters , consumption
Observing API
Usage:
var obs = NSFileHandle.Notifications.ObserveReadCompletion ((sender, args) => {
Console.WriteLine (args.AvailableData);
Console.WriteLine (args.UnixError);
});
Stop notifications:
obs.Dispose ();
Binding Notification – Two Steps
Define Notification Payload
• Optional
• Interface without [Export]
• Use EventArgs in type name
public interface NSFileHandleReadEventArgs {
[Export ("NSFileHandleNotificationDataItem")]
NSData AvailableData { get; }
[Export ("NSFileHandleError”)]
int UnixErrorCode { get; }
}
Annotate Fields
• Annotate fields with
[Notification] attribute
• Use type if you have a
payload
[Field ("NSFileHandleReadCompletionNotification")]
[Notification (typeof (NSFileHandleReadEventArgs))]
NSString ReadCompletionNotification { get; }
Generated Notifications
public class NSFileHandle {
public class Notifications {
// Return value is a token to stop receiving notifications
public static
NSObject ObserveReadCompletion
(EventHandler<MonoTouch.Foundation.NSFileHandleReadEventArgs> handler)
}
}
Usage:
NSFileHandle.Notifications.ObserveReadCompletion ((sender, args) => {
Console.WriteLine (args.AvailableData);
Console.WriteLine (args.UnixError);
});
Async
• Easy Async, turn any method of the form:
void Foo (arg1, arg2,.., argN, callback cb)
• Just add [Async] to the contract and it does:
void Foo (arg1, arg2, .., argN, callback cb)
Task FooAsync (arg1, arg2, .., argN)
• Callback must be a delegate type.
CURATED EXTENSIONS
• Add () methods, for initializing collections
• Exposing high-level APIs
• Strong typed APIs for Dictionaries
• Implement ToString ()
• Iterators and IEnumerable
Curated Extensions
Usage
• Improve the C# experience
• Expose some common
methods
(enumerators, LINQ, strong
types)
• Re-surface internal methods
Example
partial class MagicBeans {
// Enable code like this:
//
// foreach (var j in myBean){
// }
//
public IEnumerator<Bean> GetEnumerator()
{
foreach (var bean in GetAllBeans())
yield return bean;
}
}
NSDictionary As Options
• Many APIs in iOS take NSDictionary “options”
– Annoying to find acceptable keys and values
– Requires a trip to the documentation
– Often docs are bad, see StackOverflow or Google
– Invalid values are ignored or
– Generate an error with no useful information
Strong typed wrappers
• Discovery of properties with IDE’s Code
Completion.
• Let the IDE guide you
• Only valid key/values allowed
• Skip a trip to the documentation
• Avoid ping-pong in docs
• Avoid error guesswork for your users
NSDictionary vs Strong Types
With NSDictionary
var options = new NSDictionary (
AVAudioSettings.AVLinearPCMIsFloatKey,
new NSNumber (1),
AVAudioSettings.AVEncoderBitRateKey,
new NSNumber (44000));
new AVAssetReaderAudioMixOutput
(tr, options);
With Strong Types
var options = new AudioSettings () {
AVLinearPCMFloat = true,
EncoderBitRate = 44000
};
new AVAssetReaderAudioMixOutput (tr, options)
Using DictionaryContainer
• DictionaryContainer provides bridge
– Subclass DictionaryContainer
– Provide a constructor that takes NSDictionary
– Provide constructor with fresh
NSMutableDictionary
• Use GetXxxValue and SetXxxValue
DictionaryContainer Sample
public class AudioSettings : DictionaryContainer
{
public AudioSettings () : base (new NSMutableDictionary ()) {}
public AudioSettings (NSDictionary dictionary) : base (dictionary) {}
public AudioFormatType? Format {
set {
SetNumberValue (AVAudioSettings.AVFormatIDKey, (int?) value);
}
get {
return (AudioFormatType?)GetInt32Value (AVAudioSettings.AVFormatIDKey);
}
}
Expose Iterators
• Useful for LINQ
• Lets your objects be consumed by LINQ
• Implement GetEnumerator
• Use yield to invoke underlying APIs

Mais conteúdo relacionado

Mais procurados

FISL XIV - The ELF File Format and the Linux Loader
FISL XIV - The ELF File Format and the Linux LoaderFISL XIV - The ELF File Format and the Linux Loader
FISL XIV - The ELF File Format and the Linux LoaderJohn Tortugo
 
Object Oriented Programming with COBOL
Object Oriented Programming with COBOLObject Oriented Programming with COBOL
Object Oriented Programming with COBOLMicro Focus
 
Avro - More Than Just a Serialization Framework - CHUG - 20120416
Avro - More Than Just a Serialization Framework - CHUG - 20120416Avro - More Than Just a Serialization Framework - CHUG - 20120416
Avro - More Than Just a Serialization Framework - CHUG - 20120416Chicago Hadoop Users Group
 
Thrift vs Protocol Buffers vs Avro - Biased Comparison
Thrift vs Protocol Buffers vs Avro - Biased ComparisonThrift vs Protocol Buffers vs Avro - Biased Comparison
Thrift vs Protocol Buffers vs Avro - Biased ComparisonIgor Anishchenko
 
Object Oriented Cobol
Object Oriented CobolObject Oriented Cobol
Object Oriented CobolDov Keshet
 
ABC of Platform Workspace
ABC of Platform WorkspaceABC of Platform Workspace
ABC of Platform WorkspaceTomasz Zarna
 
LLVM Compiler - Link Time Optimization
LLVM Compiler - Link Time OptimizationLLVM Compiler - Link Time Optimization
LLVM Compiler - Link Time OptimizationVivek Pansara
 
.Net overviewrajnish
.Net overviewrajnish.Net overviewrajnish
.Net overviewrajnishRajnish Kalla
 
Something About Dynamic Linking
Something About Dynamic LinkingSomething About Dynamic Linking
Something About Dynamic LinkingWang Hsiangkai
 
Overview Of .Net 4.0 Sanjay Vyas
Overview Of .Net 4.0   Sanjay VyasOverview Of .Net 4.0   Sanjay Vyas
Overview Of .Net 4.0 Sanjay Vyasrsnarayanan
 
Compiler Construction | Lecture 17 | Beyond Compiler Construction
Compiler Construction | Lecture 17 | Beyond Compiler ConstructionCompiler Construction | Lecture 17 | Beyond Compiler Construction
Compiler Construction | Lecture 17 | Beyond Compiler ConstructionEelco Visser
 

Mais procurados (20)

FISL XIV - The ELF File Format and the Linux Loader
FISL XIV - The ELF File Format and the Linux LoaderFISL XIV - The ELF File Format and the Linux Loader
FISL XIV - The ELF File Format and the Linux Loader
 
Compilation
CompilationCompilation
Compilation
 
Object Oriented Programming with COBOL
Object Oriented Programming with COBOLObject Oriented Programming with COBOL
Object Oriented Programming with COBOL
 
Dynamic Linker
Dynamic LinkerDynamic Linker
Dynamic Linker
 
Avro - More Than Just a Serialization Framework - CHUG - 20120416
Avro - More Than Just a Serialization Framework - CHUG - 20120416Avro - More Than Just a Serialization Framework - CHUG - 20120416
Avro - More Than Just a Serialization Framework - CHUG - 20120416
 
Ch6
Ch6Ch6
Ch6
 
Thrift vs Protocol Buffers vs Avro - Biased Comparison
Thrift vs Protocol Buffers vs Avro - Biased ComparisonThrift vs Protocol Buffers vs Avro - Biased Comparison
Thrift vs Protocol Buffers vs Avro - Biased Comparison
 
Compiler Design Tutorial
Compiler Design Tutorial Compiler Design Tutorial
Compiler Design Tutorial
 
Object Oriented Cobol
Object Oriented CobolObject Oriented Cobol
Object Oriented Cobol
 
ABC of Platform Workspace
ABC of Platform WorkspaceABC of Platform Workspace
ABC of Platform Workspace
 
C++ overview
C++ overviewC++ overview
C++ overview
 
LLVM Compiler - Link Time Optimization
LLVM Compiler - Link Time OptimizationLLVM Compiler - Link Time Optimization
LLVM Compiler - Link Time Optimization
 
Eval4j @ JVMLS 2014
Eval4j @ JVMLS 2014Eval4j @ JVMLS 2014
Eval4j @ JVMLS 2014
 
Yacc
YaccYacc
Yacc
 
.Net overviewrajnish
.Net overviewrajnish.Net overviewrajnish
.Net overviewrajnish
 
Something About Dynamic Linking
Something About Dynamic LinkingSomething About Dynamic Linking
Something About Dynamic Linking
 
Compiler unit 1
Compiler unit 1Compiler unit 1
Compiler unit 1
 
Overview Of .Net 4.0 Sanjay Vyas
Overview Of .Net 4.0   Sanjay VyasOverview Of .Net 4.0   Sanjay Vyas
Overview Of .Net 4.0 Sanjay Vyas
 
Compiler Construction | Lecture 17 | Beyond Compiler Construction
Compiler Construction | Lecture 17 | Beyond Compiler ConstructionCompiler Construction | Lecture 17 | Beyond Compiler Construction
Compiler Construction | Lecture 17 | Beyond Compiler Construction
 
LLVM
LLVMLLVM
LLVM
 

Destaque

C# Async on iOS and Android - Craig Dunn, Developer Evangelist at Xamarin
C# Async on iOS and Android - Craig Dunn, Developer Evangelist at XamarinC# Async on iOS and Android - Craig Dunn, Developer Evangelist at Xamarin
C# Async on iOS and Android - Craig Dunn, Developer Evangelist at XamarinXamarin
 
Preservação ambiental
Preservação ambientalPreservação ambiental
Preservação ambientalSandra Alves
 
Como elaborar uma boa apresentação
Como elaborar uma boa apresentaçãoComo elaborar uma boa apresentação
Como elaborar uma boa apresentaçãomzylb
 
Slides para Apresentação acadêmica
Slides para Apresentação acadêmicaSlides para Apresentação acadêmica
Slides para Apresentação acadêmicaRafaelBorges3
 
Apresentação de slides pronto
Apresentação de slides prontoApresentação de slides pronto
Apresentação de slides prontocandidacbertao
 

Destaque (7)

How to present to Investors?
How to present to Investors?How to present to Investors?
How to present to Investors?
 
C# Async on iOS and Android - Craig Dunn, Developer Evangelist at Xamarin
C# Async on iOS and Android - Craig Dunn, Developer Evangelist at XamarinC# Async on iOS and Android - Craig Dunn, Developer Evangelist at Xamarin
C# Async on iOS and Android - Craig Dunn, Developer Evangelist at Xamarin
 
Preservação ambiental
Preservação ambientalPreservação ambiental
Preservação ambiental
 
Como elaborar uma boa apresentação
Como elaborar uma boa apresentaçãoComo elaborar uma boa apresentação
Como elaborar uma boa apresentação
 
TCC SLIDE DE APRESENTAÇÃO
TCC SLIDE DE APRESENTAÇÃOTCC SLIDE DE APRESENTAÇÃO
TCC SLIDE DE APRESENTAÇÃO
 
Slides para Apresentação acadêmica
Slides para Apresentação acadêmicaSlides para Apresentação acadêmica
Slides para Apresentação acadêmica
 
Apresentação de slides pronto
Apresentação de slides prontoApresentação de slides pronto
Apresentação de slides pronto
 

Semelhante a Binding Objective-C Libraries, Miguel de Icaza

COMMitMDE'18: Eclipse Hawk: model repository querying as a service
COMMitMDE'18: Eclipse Hawk: model repository querying as a serviceCOMMitMDE'18: Eclipse Hawk: model repository querying as a service
COMMitMDE'18: Eclipse Hawk: model repository querying as a serviceAntonio García-Domínguez
 
C++ Windows Forms L01 - Intro
C++ Windows Forms L01 - IntroC++ Windows Forms L01 - Intro
C++ Windows Forms L01 - IntroMohammad Shaker
 
Compiler Construction | Lecture 1 | What is a compiler?
Compiler Construction | Lecture 1 | What is a compiler?Compiler Construction | Lecture 1 | What is a compiler?
Compiler Construction | Lecture 1 | What is a compiler?Eelco Visser
 
What's new in Xamarin.iOS, by Miguel de Icaza
What's new in Xamarin.iOS, by Miguel de IcazaWhat's new in Xamarin.iOS, by Miguel de Icaza
What's new in Xamarin.iOS, by Miguel de IcazaXamarin
 
Open Source Swift Under the Hood
Open Source Swift Under the HoodOpen Source Swift Under the Hood
Open Source Swift Under the HoodC4Media
 
OpenSAF Symposium_Python Bindings_9.21.11
OpenSAF Symposium_Python Bindings_9.21.11OpenSAF Symposium_Python Bindings_9.21.11
OpenSAF Symposium_Python Bindings_9.21.11OpenSAF Foundation
 
Objective-c for Java Developers
Objective-c for Java DevelopersObjective-c for Java Developers
Objective-c for Java DevelopersMuhammad Abdullah
 
C++_programs.ppt
C++_programs.pptC++_programs.ppt
C++_programs.pptTeacherOnat
 
C++_programs.ppt
C++_programs.pptC++_programs.ppt
C++_programs.pptJayarAlejo
 
C++_programs.ppt
C++_programs.pptC++_programs.ppt
C++_programs.pptJayarAlejo
 
C++_programs.ppt
C++_programs.pptC++_programs.ppt
C++_programs.pptEPORI
 
C++ programming: Basic introduction to C++.ppt
C++ programming: Basic introduction to C++.pptC++ programming: Basic introduction to C++.ppt
C++ programming: Basic introduction to C++.pptyp02
 
C++_programs.ppt
C++_programs.pptC++_programs.ppt
C++_programs.pptInfotech27
 
ASP.NET Session 3
ASP.NET Session 3ASP.NET Session 3
ASP.NET Session 3Sisir Ghosh
 
Compiler Construction
Compiler ConstructionCompiler Construction
Compiler ConstructionAhmed Raza
 

Semelhante a Binding Objective-C Libraries, Miguel de Icaza (20)

Intro to .NET and Core C#
Intro to .NET and Core C#Intro to .NET and Core C#
Intro to .NET and Core C#
 
COMMitMDE'18: Eclipse Hawk: model repository querying as a service
COMMitMDE'18: Eclipse Hawk: model repository querying as a serviceCOMMitMDE'18: Eclipse Hawk: model repository querying as a service
COMMitMDE'18: Eclipse Hawk: model repository querying as a service
 
C# tutorial
C# tutorialC# tutorial
C# tutorial
 
C++ Windows Forms L01 - Intro
C++ Windows Forms L01 - IntroC++ Windows Forms L01 - Intro
C++ Windows Forms L01 - Intro
 
Compiler Construction | Lecture 1 | What is a compiler?
Compiler Construction | Lecture 1 | What is a compiler?Compiler Construction | Lecture 1 | What is a compiler?
Compiler Construction | Lecture 1 | What is a compiler?
 
What's new in Xamarin.iOS, by Miguel de Icaza
What's new in Xamarin.iOS, by Miguel de IcazaWhat's new in Xamarin.iOS, by Miguel de Icaza
What's new in Xamarin.iOS, by Miguel de Icaza
 
Open Source Swift Under the Hood
Open Source Swift Under the HoodOpen Source Swift Under the Hood
Open Source Swift Under the Hood
 
Monkey space 2013
Monkey space 2013Monkey space 2013
Monkey space 2013
 
OpenSAF Symposium_Python Bindings_9.21.11
OpenSAF Symposium_Python Bindings_9.21.11OpenSAF Symposium_Python Bindings_9.21.11
OpenSAF Symposium_Python Bindings_9.21.11
 
Objective-c for Java Developers
Objective-c for Java DevelopersObjective-c for Java Developers
Objective-c for Java Developers
 
C#: Past, Present and Future
C#: Past, Present and FutureC#: Past, Present and Future
C#: Past, Present and Future
 
C++_programs.ppt
C++_programs.pptC++_programs.ppt
C++_programs.ppt
 
C++_programs.ppt
C++_programs.pptC++_programs.ppt
C++_programs.ppt
 
C++_programs.ppt
C++_programs.pptC++_programs.ppt
C++_programs.ppt
 
C++_programs.ppt
C++_programs.pptC++_programs.ppt
C++_programs.ppt
 
C++_programs.ppt
C++_programs.pptC++_programs.ppt
C++_programs.ppt
 
C++ programming: Basic introduction to C++.ppt
C++ programming: Basic introduction to C++.pptC++ programming: Basic introduction to C++.ppt
C++ programming: Basic introduction to C++.ppt
 
C++_programs.ppt
C++_programs.pptC++_programs.ppt
C++_programs.ppt
 
ASP.NET Session 3
ASP.NET Session 3ASP.NET Session 3
ASP.NET Session 3
 
Compiler Construction
Compiler ConstructionCompiler Construction
Compiler Construction
 

Mais de Xamarin

Xamarin University Presents: Building Your First Intelligent App with Xamarin...
Xamarin University Presents: Building Your First Intelligent App with Xamarin...Xamarin University Presents: Building Your First Intelligent App with Xamarin...
Xamarin University Presents: Building Your First Intelligent App with Xamarin...Xamarin
 
Xamarin University Presents: Ship Better Apps with Visual Studio App Center
Xamarin University Presents: Ship Better Apps with Visual Studio App CenterXamarin University Presents: Ship Better Apps with Visual Studio App Center
Xamarin University Presents: Ship Better Apps with Visual Studio App CenterXamarin
 
Get the Most Out of iOS 11 with Visual Studio Tools for Xamarin
Get the Most Out of iOS 11 with Visual Studio Tools for XamarinGet the Most Out of iOS 11 with Visual Studio Tools for Xamarin
Get the Most Out of iOS 11 with Visual Studio Tools for XamarinXamarin
 
Get the Most out of Android 8 Oreo with Visual Studio Tools for Xamarin
Get the Most out of Android 8 Oreo with Visual Studio Tools for XamarinGet the Most out of Android 8 Oreo with Visual Studio Tools for Xamarin
Get the Most out of Android 8 Oreo with Visual Studio Tools for XamarinXamarin
 
Creative Hacking: Delivering React Native App A/B Testing Using CodePush
Creative Hacking: Delivering React Native App A/B Testing Using CodePushCreative Hacking: Delivering React Native App A/B Testing Using CodePush
Creative Hacking: Delivering React Native App A/B Testing Using CodePushXamarin
 
Build Better Games with Unity and Microsoft Azure
Build Better Games with Unity and Microsoft AzureBuild Better Games with Unity and Microsoft Azure
Build Better Games with Unity and Microsoft AzureXamarin
 
Exploring UrhoSharp 3D with Xamarin Workbooks
Exploring UrhoSharp 3D with Xamarin WorkbooksExploring UrhoSharp 3D with Xamarin Workbooks
Exploring UrhoSharp 3D with Xamarin WorkbooksXamarin
 
Desktop Developer’s Guide to Mobile with Visual Studio Tools for Xamarin
Desktop Developer’s Guide to Mobile with Visual Studio Tools for XamarinDesktop Developer’s Guide to Mobile with Visual Studio Tools for Xamarin
Desktop Developer’s Guide to Mobile with Visual Studio Tools for XamarinXamarin
 
Developer’s Intro to Azure Machine Learning
Developer’s Intro to Azure Machine LearningDeveloper’s Intro to Azure Machine Learning
Developer’s Intro to Azure Machine LearningXamarin
 
Customizing Xamarin.Forms UI
Customizing Xamarin.Forms UICustomizing Xamarin.Forms UI
Customizing Xamarin.Forms UIXamarin
 
Session 4 - Xamarin Partner Program, Events and Resources
Session 4 - Xamarin Partner Program, Events and ResourcesSession 4 - Xamarin Partner Program, Events and Resources
Session 4 - Xamarin Partner Program, Events and ResourcesXamarin
 
Session 3 - Driving Mobile Growth and Profitability
Session 3 - Driving Mobile Growth and ProfitabilitySession 3 - Driving Mobile Growth and Profitability
Session 3 - Driving Mobile Growth and ProfitabilityXamarin
 
Session 2 - Emerging Technologies in your Mobile Practice
Session 2 - Emerging Technologies in your Mobile PracticeSession 2 - Emerging Technologies in your Mobile Practice
Session 2 - Emerging Technologies in your Mobile PracticeXamarin
 
Session 1 - Transformative Opportunities in Mobile and Cloud
Session 1 - Transformative Opportunities in Mobile and Cloud Session 1 - Transformative Opportunities in Mobile and Cloud
Session 1 - Transformative Opportunities in Mobile and Cloud Xamarin
 
SkiaSharp Graphics for Xamarin.Forms
SkiaSharp Graphics for Xamarin.FormsSkiaSharp Graphics for Xamarin.Forms
SkiaSharp Graphics for Xamarin.FormsXamarin
 
Building Games for iOS, macOS, and tvOS with Visual Studio and Azure
Building Games for iOS, macOS, and tvOS with Visual Studio and AzureBuilding Games for iOS, macOS, and tvOS with Visual Studio and Azure
Building Games for iOS, macOS, and tvOS with Visual Studio and AzureXamarin
 
Intro to Xamarin.Forms for Visual Studio 2017
Intro to Xamarin.Forms for Visual Studio 2017Intro to Xamarin.Forms for Visual Studio 2017
Intro to Xamarin.Forms for Visual Studio 2017Xamarin
 
Connected Mobile Apps with Microsoft Azure
Connected Mobile Apps with Microsoft AzureConnected Mobile Apps with Microsoft Azure
Connected Mobile Apps with Microsoft AzureXamarin
 
Introduction to Xamarin for Visual Studio 2017
Introduction to Xamarin for Visual Studio 2017Introduction to Xamarin for Visual Studio 2017
Introduction to Xamarin for Visual Studio 2017Xamarin
 
Building Your First iOS App with Xamarin for Visual Studio
Building Your First iOS App with Xamarin for Visual StudioBuilding Your First iOS App with Xamarin for Visual Studio
Building Your First iOS App with Xamarin for Visual StudioXamarin
 

Mais de Xamarin (20)

Xamarin University Presents: Building Your First Intelligent App with Xamarin...
Xamarin University Presents: Building Your First Intelligent App with Xamarin...Xamarin University Presents: Building Your First Intelligent App with Xamarin...
Xamarin University Presents: Building Your First Intelligent App with Xamarin...
 
Xamarin University Presents: Ship Better Apps with Visual Studio App Center
Xamarin University Presents: Ship Better Apps with Visual Studio App CenterXamarin University Presents: Ship Better Apps with Visual Studio App Center
Xamarin University Presents: Ship Better Apps with Visual Studio App Center
 
Get the Most Out of iOS 11 with Visual Studio Tools for Xamarin
Get the Most Out of iOS 11 with Visual Studio Tools for XamarinGet the Most Out of iOS 11 with Visual Studio Tools for Xamarin
Get the Most Out of iOS 11 with Visual Studio Tools for Xamarin
 
Get the Most out of Android 8 Oreo with Visual Studio Tools for Xamarin
Get the Most out of Android 8 Oreo with Visual Studio Tools for XamarinGet the Most out of Android 8 Oreo with Visual Studio Tools for Xamarin
Get the Most out of Android 8 Oreo with Visual Studio Tools for Xamarin
 
Creative Hacking: Delivering React Native App A/B Testing Using CodePush
Creative Hacking: Delivering React Native App A/B Testing Using CodePushCreative Hacking: Delivering React Native App A/B Testing Using CodePush
Creative Hacking: Delivering React Native App A/B Testing Using CodePush
 
Build Better Games with Unity and Microsoft Azure
Build Better Games with Unity and Microsoft AzureBuild Better Games with Unity and Microsoft Azure
Build Better Games with Unity and Microsoft Azure
 
Exploring UrhoSharp 3D with Xamarin Workbooks
Exploring UrhoSharp 3D with Xamarin WorkbooksExploring UrhoSharp 3D with Xamarin Workbooks
Exploring UrhoSharp 3D with Xamarin Workbooks
 
Desktop Developer’s Guide to Mobile with Visual Studio Tools for Xamarin
Desktop Developer’s Guide to Mobile with Visual Studio Tools for XamarinDesktop Developer’s Guide to Mobile with Visual Studio Tools for Xamarin
Desktop Developer’s Guide to Mobile with Visual Studio Tools for Xamarin
 
Developer’s Intro to Azure Machine Learning
Developer’s Intro to Azure Machine LearningDeveloper’s Intro to Azure Machine Learning
Developer’s Intro to Azure Machine Learning
 
Customizing Xamarin.Forms UI
Customizing Xamarin.Forms UICustomizing Xamarin.Forms UI
Customizing Xamarin.Forms UI
 
Session 4 - Xamarin Partner Program, Events and Resources
Session 4 - Xamarin Partner Program, Events and ResourcesSession 4 - Xamarin Partner Program, Events and Resources
Session 4 - Xamarin Partner Program, Events and Resources
 
Session 3 - Driving Mobile Growth and Profitability
Session 3 - Driving Mobile Growth and ProfitabilitySession 3 - Driving Mobile Growth and Profitability
Session 3 - Driving Mobile Growth and Profitability
 
Session 2 - Emerging Technologies in your Mobile Practice
Session 2 - Emerging Technologies in your Mobile PracticeSession 2 - Emerging Technologies in your Mobile Practice
Session 2 - Emerging Technologies in your Mobile Practice
 
Session 1 - Transformative Opportunities in Mobile and Cloud
Session 1 - Transformative Opportunities in Mobile and Cloud Session 1 - Transformative Opportunities in Mobile and Cloud
Session 1 - Transformative Opportunities in Mobile and Cloud
 
SkiaSharp Graphics for Xamarin.Forms
SkiaSharp Graphics for Xamarin.FormsSkiaSharp Graphics for Xamarin.Forms
SkiaSharp Graphics for Xamarin.Forms
 
Building Games for iOS, macOS, and tvOS with Visual Studio and Azure
Building Games for iOS, macOS, and tvOS with Visual Studio and AzureBuilding Games for iOS, macOS, and tvOS with Visual Studio and Azure
Building Games for iOS, macOS, and tvOS with Visual Studio and Azure
 
Intro to Xamarin.Forms for Visual Studio 2017
Intro to Xamarin.Forms for Visual Studio 2017Intro to Xamarin.Forms for Visual Studio 2017
Intro to Xamarin.Forms for Visual Studio 2017
 
Connected Mobile Apps with Microsoft Azure
Connected Mobile Apps with Microsoft AzureConnected Mobile Apps with Microsoft Azure
Connected Mobile Apps with Microsoft Azure
 
Introduction to Xamarin for Visual Studio 2017
Introduction to Xamarin for Visual Studio 2017Introduction to Xamarin for Visual Studio 2017
Introduction to Xamarin for Visual Studio 2017
 
Building Your First iOS App with Xamarin for Visual Studio
Building Your First iOS App with Xamarin for Visual StudioBuilding Your First iOS App with Xamarin for Visual Studio
Building Your First iOS App with Xamarin for Visual Studio
 

Último

Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 

Último (20)

Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 

Binding Objective-C Libraries, Miguel de Icaza

  • 2. Agenda • When to Bind • How to bind • Improving the binding
  • 4. Xamarin.iOS Native Interop • Consume Objective-C or C code – Integrated existing code – Move performance sensitive code to C/assembly – Adopt third party libraries – Adopt third party controls/frameworks • At the core of Xamarin.iOS itself
  • 5. Integration with Native Libraries • iOS Native Libraries – Core libraries written in C – High-level libraries written in Objective-C • Consuming C Libraries: – Uses standard .NET Platform/Invoke support • Consuming Objective-C Libraries: – Binding Projects – “Projects” Objective-C to C# – Provides full integration with native object hierarchy
  • 6. Mono/Objective-C Bindings • Used by MonoTouch itself – Every Objective-C API is surfaced this way. • Tool produces C# libraries that: – Map 1:1 to underlying Objective-C libraries – Allow instantiating Objective-C classes – Allow subclassing/overwriting of behavior – Can extend Objective-C with C# idioms
  • 8. Header Files + Namespace
  • 11. Creating a Binding • Enumerations and Structures – Contain core definitions used by the interface • C# Interface Definition – Defines how to project Objective-C to C# – Name mapping, Overloads • Curated Extensions: – Contains helper features to simplify development – Add strongly-typed features
  • 12. Example: C# Interface Definition Objective-C @interface MagicBeans : NSObject { // … } -(id) initWithString:(NSString*)msg; +(NSArray*) getAllBeans(); -(void) grow; -(void) harvest:(NSDate *) time; @end
  • 13. Example: C# Interface Definition Objective-C @interface MagicBeans : NSObject { // … } -(id) initWithString:(NSString*)msg; +(NSArray*) getAllBeans(); -(void) grow; -(void) harvest: (NSDate *) time; @end C# Interface Definition [BaseType (typeof (NSObject))] Interface MagicBean { [Export (“initWithString:”)] IntPtr Constructor (string msg); [Static, Export (“getAllBeans”)] MagicBeans [] GetAllBeans (); [Export (“grow”)] void Grow (); [Export (“harvest:”)] void Harvest (NSDate time); }
  • 14. Binding “MagicBeans” library MagicBeans.dll Enumerations, Structures C# Interface Definition Curated Extensions libMagicBeans.a C# Source Native Binary .NET Binary Single deployment unit Contains: • C# binding • Native Library • Assets (artwork, audio)
  • 16. Compiler Driven Bindings • ObjectiveSharpie Tool – Uses LLVM’s Objective-C compiler to parse API – Applies standard Binding rules – Generates Baseline C# IDL for you – Then you modify • Available Today – http://bit.ly/objective-sharpie
  • 18. Basics of Bindings • Binding Classes • Binding Protocols • Methods, Properties – Type mappings – Arrays – Strings • Delegate classes (and Events) • Exposing Weak and Strong Types • Binding Blocks
  • 19. Class Declarations Objective-C C# Mapping Result Class Declarati on @interface Foo : Bar [BaseType (typeof (Bar))] interfaceFoo C# class Class adopting protocol @interface Foo : Bar <Pro> [BaseType (typeof (Bar))] interfaceFoo : Pro C# class, inlined protocol methods Protocol @protocol Foo <Bar> [BaseType (typeof (Bar))] [Model] interface Foo C# class with methods to override Category @interface Foo(Cute) [BaseType (typeof (Foo))] interface Cute C# extensions method class
  • 20. Objective-C Method Selectors -(float) getNumber; • Meaning: – “-” means it is an instance method – Float return type – Selector name is “getNumber” • C# IDL: *Export (“getNumber”)+ float GetNumber ();
  • 21. Objective-C Method Selectors +(float) add:(int) first and:(int) second; • Meaning: – “+” means it is a static method – Float return type – Takes two int arguments – Selector name is “add:and:” • C# IDL: *Export (“add:and:”)+ float Add (int first, int second)
  • 22. Objective-C Property Selectors @property (readwrite) int foo; • Meaning: – Property is read/write – int return type – Selector pair is: “foo” (get) and “setFoo:” (set) • C# IDL: *Export (“foo”)+ int Foo { get; set; }
  • 23. Binding Correctness • [Export] definitions might have errors – Transcription errors – Accidental setters, or wrong getters • Create a unit test – Subclass ApiCtorInitTest
  • 24. Testing your APIs [TestFixture] public class BindingCtorTest : ApiCtorInitTest { protected override Assembly Assembly { get { return typeof (CCAccelAmplitude).Assembly; } } } }
  • 25. Core Type Mappings Objective-C C# BOOL, GLBoolean bool NSString * C# string or NSString char * [PlainString] string NSInteger, NSUInteger int, uint CGRect, CGPoint, CGSize RectangleF, PointF, SizeF id NSObject SEL ObjCRuntime.Selector dispatch_queue_t CoreFoundation.DispatchQueue CGFloat, GLFloat float
  • 26. Arrays • NSArray represents arrays – Untyped, no code completion • When binding, use strong types instead – “NSArray” becomes “UIView *+” – Requires a trip to the documentation
  • 28. Linking Libraries • Use assembly-level attribute LinkWith – [assembly:LinkWith (…) • Specify static and dynamic dependencies – Frameworks (for required dependencies) – WeakFrameworks (for optional dependencies) – Pass system linker flags • Libraries referenced are bundled into DLL – Simplifies distribution (single DLL contains all resources) – Unpacked before the final build
  • 29. Native Libraries • FAT libraries – One libFoo.a may contain x86, arm, thumb code – Not all libraries build have all targets – Make sure you build all the supported targets – See monotouch-bindings’ Makefile for samples • IDE automatically examines fat libraries – And produces the proper LinkWith attribute
  • 30. New: SmartLink • By default, all native code is linked-in • SmartLink merges Mono and System linker – Only code that is directly referenced is included – Caveat: dynamic Objective-C code can fail – Big savings
  • 31. SmartLink effect on Samples - 2,000 4,000 6,000 All code Smart Linking
  • 34. Binding Public Variables • Mapped to properties in C# • Use the Field attribute. • Provide get or get/set [Field (“FooServiceKey”, “__Internal”)] NSString ServiceKey { get; set; } • Use “__Internal” for binding libraries • Supports NSArray, NSString, int, long, float, double, IntPtr and System.Drawing.SizeF
  • 35. Notifications • Basic API: – NSNotificationCenter takes a string + method – Invokes method when notification is posted – Contains an NSDictionary with notification data • We want a strongly typed API: – Simplify discovery of available notifications – Simplify discovery of parameters , consumption
  • 36. Observing API Usage: var obs = NSFileHandle.Notifications.ObserveReadCompletion ((sender, args) => { Console.WriteLine (args.AvailableData); Console.WriteLine (args.UnixError); }); Stop notifications: obs.Dispose ();
  • 37. Binding Notification – Two Steps Define Notification Payload • Optional • Interface without [Export] • Use EventArgs in type name public interface NSFileHandleReadEventArgs { [Export ("NSFileHandleNotificationDataItem")] NSData AvailableData { get; } [Export ("NSFileHandleError”)] int UnixErrorCode { get; } } Annotate Fields • Annotate fields with [Notification] attribute • Use type if you have a payload [Field ("NSFileHandleReadCompletionNotification")] [Notification (typeof (NSFileHandleReadEventArgs))] NSString ReadCompletionNotification { get; }
  • 38. Generated Notifications public class NSFileHandle { public class Notifications { // Return value is a token to stop receiving notifications public static NSObject ObserveReadCompletion (EventHandler<MonoTouch.Foundation.NSFileHandleReadEventArgs> handler) } } Usage: NSFileHandle.Notifications.ObserveReadCompletion ((sender, args) => { Console.WriteLine (args.AvailableData); Console.WriteLine (args.UnixError); });
  • 39. Async • Easy Async, turn any method of the form: void Foo (arg1, arg2,.., argN, callback cb) • Just add [Async] to the contract and it does: void Foo (arg1, arg2, .., argN, callback cb) Task FooAsync (arg1, arg2, .., argN) • Callback must be a delegate type.
  • 41. • Add () methods, for initializing collections • Exposing high-level APIs • Strong typed APIs for Dictionaries • Implement ToString () • Iterators and IEnumerable
  • 42. Curated Extensions Usage • Improve the C# experience • Expose some common methods (enumerators, LINQ, strong types) • Re-surface internal methods Example partial class MagicBeans { // Enable code like this: // // foreach (var j in myBean){ // } // public IEnumerator<Bean> GetEnumerator() { foreach (var bean in GetAllBeans()) yield return bean; } }
  • 43. NSDictionary As Options • Many APIs in iOS take NSDictionary “options” – Annoying to find acceptable keys and values – Requires a trip to the documentation – Often docs are bad, see StackOverflow or Google – Invalid values are ignored or – Generate an error with no useful information
  • 44. Strong typed wrappers • Discovery of properties with IDE’s Code Completion. • Let the IDE guide you • Only valid key/values allowed • Skip a trip to the documentation • Avoid ping-pong in docs • Avoid error guesswork for your users
  • 45. NSDictionary vs Strong Types With NSDictionary var options = new NSDictionary ( AVAudioSettings.AVLinearPCMIsFloatKey, new NSNumber (1), AVAudioSettings.AVEncoderBitRateKey, new NSNumber (44000)); new AVAssetReaderAudioMixOutput (tr, options); With Strong Types var options = new AudioSettings () { AVLinearPCMFloat = true, EncoderBitRate = 44000 }; new AVAssetReaderAudioMixOutput (tr, options)
  • 46. Using DictionaryContainer • DictionaryContainer provides bridge – Subclass DictionaryContainer – Provide a constructor that takes NSDictionary – Provide constructor with fresh NSMutableDictionary • Use GetXxxValue and SetXxxValue
  • 47. DictionaryContainer Sample public class AudioSettings : DictionaryContainer { public AudioSettings () : base (new NSMutableDictionary ()) {} public AudioSettings (NSDictionary dictionary) : base (dictionary) {} public AudioFormatType? Format { set { SetNumberValue (AVAudioSettings.AVFormatIDKey, (int?) value); } get { return (AudioFormatType?)GetInt32Value (AVAudioSettings.AVFormatIDKey); } }
  • 48. Expose Iterators • Useful for LINQ • Lets your objects be consumed by LINQ • Implement GetEnumerator • Use yield to invoke underlying APIs