SlideShare a Scribd company logo
1 of 78
training@instil.co
ACCU - November 2019
ยฉ Instil Software 2019
Interop Between Kotlin Native and C / Swift
The Good, the Bad and the Ugly @BoyleEamonn
Eamonn Boyle
@GarthGilmour
Garth Gilmour
Me
Him
Us
Google Maps
2010: Work begins on Kotlin within JetBrains
2011: First public announcement on Kotlin
2012: Open sourced under Apache 2 license
2016: Version one released
2017: First class support on Android
2018: Version 1.3 released
A Kotlin Timeline
Weโ€™ve bought into Kotlin in a big way
Kotlinโ€ฆOkโ€ฆweโ€™re obsessed
We held a workshop at the conference
โ€ข React App with Kotlin on Server & Browser
Kotlinโ€ฆOkโ€ฆweโ€™re obsessed
Weโ€™re going back againโ€ฆ
If youโ€™re working on the Java Virtual Machine, try not to use Java
Having done C# for many years I was so happy to see Kotlin for the JVM
Problems with Java
โ€ข Verbose, Verbose, Verbose, Verbose, Verbose, Verbose, Verbose, Verbose,
โ€ข Nulls
โ€ข Completely OO
Why Kotlin - Java โ€“ Yuck!
No need to wait - the interop story is so good
โ€ข Call into all that legacy Java code easily
โ€ข Call into your new Kotlin code from Java easily
Really concise, yet clear syntax
โ€ข Less is more
โ€ข โ€œBorrowsโ€ the best bits of other languages
โ€ข Less baggage
Why Kotlin โ€“ So Much to Like
Null Safety
String Templates
Default parameters
Extensions
Free Functions
Coroutines
Single Expression Functions
Reified generics
Data classes and Properties
Type Inference
Smart Casts
Operator overloading
Basic Model Classes โ€“ Java
public class Movie {
private String title;
private String description;
private Rating rating;
private Genre genre;
}
Basic Model Classes โ€“ Java
public class Movie {
private String title;
private String description;
private Rating rating;
private Genre genre;
public Movie(String title, String description, Rating rating, Genre genre) {
this.title = title;
this.description = description;
this.rating = rating;
this.genre = genre;
}
}
Basic Model Classes โ€“ Java
public class Movie {
private String title;
private String description;
private Rating rating;
private Genre genre;
public Movie(String title, String description, Rating rating, Genre genre) {
this.title = title;
this.description = description;
this.rating = rating;
this.genre = genre;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
Basic Model Classes โ€“ Java
public class Movie {
private String title;
private String description;
private Rating rating;
private Genre genre;
public Movie(String title, String description, Rating rating, Genre genre) {
this.title = title;
this.description = description;
this.rating = rating;
this.genre = genre;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Rating getRating() {
return rating;
}
public void setRating(Rating rating) {
this.rating = rating;
}
public Genre getGenre() {
return genre;
}
public void setGenre(Genre genre) {
this.genre = genre;
}
}
Basic Model Classes โ€“ Java vs Kotlin
public class Movie {
private String title;
private String description;
private Rating rating;
private Genre genre;
public Movie(String title, String description, Rating rating, Genre genre) {
this.title = title;
this.description = description;
this.rating = rating;
this.genre = genre;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Rating getRating() {
return rating;
}
public void setRating(Rating rating) {
this.rating = rating;
}
public Genre getGenre() {
return genre;
}
public void setGenre(Genre genre) {
this.genre = genre;
}
}
data class Movie(var title: String,
var description: String,
var rating: Rating,
var genre: Genre) {
}
Java Kotlin
Basic Model Classes โ€“ Java vs Kotlin
import java.util.Objects;
public class Movie {
private String title;
private String description;
private Rating rating;
private Genre genre;
public Movie(String title, String description, Rating rating, Genre genre) {
this.title = title;
this.description = description;
this.rating = rating;
this.genre = genre;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Rating getRating() {
return rating;
}
public void setRating(Rating rating) {
this.rating = rating;
}
public Genre getGenre() {
return genre;
}
public void setGenre(Genre genre) {
this.genre = genre;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Movie movie = (Movie) o;
return Objects.equals(title, movie.title) &&
Objects.equals(description, movie.description) &&
Objects.equals(rating, movie.rating) &&
Objects.equals(genre, movie.genre);
}
@Override
public int hashCode() {
return Objects.hash(title, description, rating, genre);
}
@Override
public String toString() {
return "Movie{" +
"title='" + title + ''' +
", description='" + description + ''' +
", rating=" + rating +
", genre=" + genre +
'}';
}
}
data class Movie(var title: String,
var description: String,
var rating: Rating,
var genre: Genre) {
}
We also get hashCode(), equals(), toString() and moreโ€ฆ
External libraries and tools like Lombok will help with Java
Java Kotlin
Null Safety
private fun processUserPolicy(user: User) {
val policy = user.policy
if (policy.isComplete) {
policyProcessor.process(policy)
}
}
private static void processUserPolicy(User user) {
if (user != null && user.getPolicy() != null) {
Policy policy = user.getPolicy();
if (policy.isComplete()) {
policyProcessor.process(policy);
}
}
}
Java
Kotlin
Functional Chaining โ€“ vs Java
Reified Generics with a single primitive representation makes the code simpler
double averageSalary = employees
.stream()
.filter(x ->
x.getDepartment() == Engineering)
.mapToInt(Employee::getSalary)
.average()
.orElse(0);
Java
val averageSalary = employees
.filter { it.department === Engineering }
.map { it.salary }
.average()
Kotlin
Kotlin was originally for writing server and desktop Java
โ€ข Thatโ€™s what JetBrains were building themselves
This evolved further into supporting Android
โ€ข Which is now what itโ€™s very popular for
JetBrains went further to support the Browser in Kotlin/JS and native in
Kotlin.Native
Kotlin Platforms
Kotlin/Native is a technology for compiling Kotlin code to native binaries
โ€ข It runs without a virtual machine
โ€ข The output is NOT portable
Although the binary output is not portable, the source IS portable
โ€ข The compiler can compile the same source to multiple outputs/platforms
โ€ข The source can be placed into a multiplatform project and used for JVM,
JS etc
Kotlin Native
Kotlin Compiler LLVMSource Native Binary
LLVM IR
Supported platforms include,
โ€ข iOS (arm32, arm64, emulator x86_64)
โ€ข MacOS (x86_64)
โ€ข Android (arm32, arm64)
โ€ข Windows (mingw x86_64)
โ€ข Linux (x86_64, arm32, MIPS, MIPS little endian, Raspberry Pi)
โ€ข WebAssembly (wasm32)
We can link to or dynamically call into other native libraries
โ€ข C, Swift or ObjectiveC libraries
Note โ€“ Kotlin/Native is still beta
Kotlin Native
Scenarios
Kotlin Native
Executable
Kotlin Native
Library
Platform Native
Executable
Kotlin Native
Executable
Platform Native
Library
Multiplatform Project
Executable or Library
Multiple Targets in One Project
Common Code
Platform Specific Code
iOS Android
You can drive everything from the command line
โ€ข Kotlin Native CLI tools
โ€ข Gradle for fully builder system
An IDE can make the whole experience much easier
IDEs
Common JVM APIs such as kotlin.io arenโ€™t available
But there are multi-platform and native libraries that you can consume
Kotlin Native also supports excellent interop with C and ObjectiveC/Swift
API compatibility shown on doc pages
Supported APIs
import kotlinx.io.*
import kotlinx.cinterop.*
To simplify things further, common native APIs have already been wrapped
These bindings are platform specific but include
โ€ข Posix
โ€ข zlib
โ€ข GDI (Windows)
โ€ข OpenGL
โ€ข Apple Frameworks
Platform Libraries
import platform.posix.*
A major reason for choosing Kotlin is that it is a great language
For Kotlin Native, the language remains unchanged
โ€ข Though the implementation and runtime is wildly different
In native, it uses reference counting for automated memory management
โ€ข And an additional cyclical garbage collector
Advantages of the Kotlin Language
Letโ€™s have a look at native features and along the
way see some nice features of the language
generally
Advantages of the Kotlin Language
ยฉ Instil Software 2019
โ€ข Kotlin Native Examples
Demo
Scenarios
Kotlin Native
Executable
Dynamic Library
C & C++
Apple
Framework
Swift
Bitwise Operations
Data can be copied back and forth between Kotlin and C
โ€ข Kotlin Native can automatically marshal from C primitive types
Primitive Types
C Kotlin
char kotlin.Byte
unsigned char kotlin.UByte
short kotlin.Short
unsigned short kotlin.UShort
int kotlin.Int
unsigned int kotlin.UInt
long long kotlin.Long
unsigned long long kotlin.ULong
float kotlin.Float
double kotlin.Double
If directly referencing C data, Kotlin Native uses a CVariable type
Internally, it contains a reference to C data via a NativePtr type
โ€ข You can think of it a little like a wrapper or C++ reference or lvalue
CVariable
CVariable
NativePtr
0x02677dd0
Kotlin Native
0x0000000002677d00 00000000 00000000 581cbfec 7a7b0430 โ”‚ ยทยทยทยทยทยทยทยทXยทยทยทz{ยท0 โ”‚
0x0000000002677d10 107d6702 00000000 587d6702 00000000 โ”‚ ยท}gยทยทยทยทยทX}gยทยทยทยทยท โ”‚
0x0000000002677d20 abababab abababab abababab abababab โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚
0x0000000002677d30 00000000 00000000 00000000 00000000 โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚
0x0000000002677d40 eefeeefe eefeeefe 581cbfec 7b7b0430 โ”‚ ยทยทยทยทยทยทยทยทXยทยทยท{{ยท0 โ”‚
0x0000000002677d50 0d000000 04080000 30aa4700 00000000 โ”‚ ยทยทยทยทยทยทยทยท0ยทGยทยทยทยทยท โ”‚
0x0000000002677d60 abababab abababab abababab abababab โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚
0x0000000002677d70 00000000 00000000 00000000 00000000 โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚
0x0000000002677d80 00000000 00000000 581cbfec 7b7b0437 โ”‚ ยทยทยทยทยทยทยทยทXยทยทยท{{ยท7 โ”‚
0x0000000002677d90 00000000 00000000 00ababab abababab โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚
0x0000000002677da0 abababab abababab ab000000 00000000 โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚
0x0000000002677db0 00000000 00000000 00000000 00000000 โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚
0x0000000002677dc0 00000000 00000000 7c1cbccb 7b7b0400 โ”‚ ยทยทยทยทยทยทยทยท|ยทยทยท{{ยทยท โ”‚
0x0000000002677dd0 b05f0201 00000000 e0200201 00000000 โ”‚ ยท_ยทยทยทยทยทยทยท ยทยทยทยทยทยท โ”‚
0x0000000002677de0 eefeeefe eefeeefe eefeeefe eefeeefe โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚
0x0000000002677df0 eefeeefe eefeeefe eefeeefe eefeeefe โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚
There are CVariable types for,
โ€ข All the primitives - IntVar, DoubleVar etc
โ€ข Enums โ€“ CEnumVar<T>
โ€ข Structs โ€“ CStructVar<T>
โ€ข Pointers (more on this later) โ€“ CPointerVar<T>
CVariables allow reading and writing via the value property
CVariable Types
fun sum(total: IntVar, current: Int) {
total.value += current
}
CVariable Types
CPointed
NativePointed
CEnumVar
BooleanVar
ByteVar
ShortVar
IntVar
LongVar
FloatVar
DoubleVar
. . .
CStructVar CPrimitiveVarCPointerVar
CVariable CFunction
Structs can be easily created in C and mapped to Kotlin
โ€ข The mapping is done automatically by including headers in the def file
Structs
class Employee(rawPtr: NativePtr) : CStructVar(rawPtr) {
companion object : Type(24, 8)
var name: CPointer<ByteVar>?
get() = memberAt<CPointerVar<ByteVar>>(0).value
set(value) { memberAt<CPointerVar<ByteVar>>(0).value = value }
var age: Int
get() = memberAt<IntVar>(8).value
set(value) { memberAt<IntVar>(8).value = value }
var salary: Double
get() = memberAt<DoubleVar>(16).value
set(value) { memberAt<DoubleVar>(16).value = value }
}
typedef struct {
char* name;
int age;
double salary;
} Employee;
The type name matches the C typedef but it is a CStructVar
Structs โ€“ Points to Note
class Employee(rawPtr: NativePtr) : CStructVar(rawPtr) {
companion object : Type(24, 8)
...
}
typedef struct {
char* name;
int age;
double salary;
} Employee;
Internally it uses addresses to get CVariables but marshals into Kotlin types
Structs โ€“ Points to Note
class Employee(rawPtr: NativePtr) : CStructVar(rawPtr) {
...
var age: Int
get() = memberAt<IntVar>(8).value
set(value) { memberAt<IntVar>(8).value = value }
var salary: Double
get() = memberAt<DoubleVar>(16).value
set(value) { memberAt<DoubleVar>(16).value = value }
} typedef struct {
char* name;
int age;
double salary;
} Employee;
Except where the returned type is a C type
โ€ข E.g. pointers
Structs โ€“ Points to Note
class Employee(rawPtr: NativePtr) : CStructVar(rawPtr) {
var name: CPointer<ByteVar>?
get() = memberAt<CPointerVar<ByteVar>>(0).value
set(value) { memberAt<CPointerVar<ByteVar>>(0).value = value }
...
}
typedef struct {
char* name;
int age;
double salary;
} Employee;
You will note that structs have a Type that includes size and alignment info
This facilitates allocation
Allocating Structs
class Employee(rawPtr: NativePtr)
: CStructVar(rawPtr) {
companion object : Type(24, 8)
...
}
typedef struct {
char* name;
int age;
double salary;
} Employee;
Pointers
https://xkcd.com/138/
As well as CVariables, Kotlin Native supports pointers via CPointer<T>
The type of data pointed to, T, must be a CVariable type
โ€ข Itโ€™s actually CPointed which can be a CFunction, but more on that later
Pointers
Kotlin Native
0x0000000002677d00 00000000 00000000 581cbfec 7a7b0430 โ”‚ ยทยทยทยทยทยทยทยทXยทยทยทz{ยท0 โ”‚
0x0000000002677d10 107d6702 00000000 587d6702 00000000 โ”‚ ยท}gยทยทยทยทยทX}gยทยทยทยทยท โ”‚
0x0000000002677d20 abababab abababab abababab abababab โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚
0x0000000002677d30 00000000 00000000 00000000 00000000 โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚
0x0000000002677d40 eefeeefe eefeeefe 581cbfec 7b7b0430 โ”‚ ยทยทยทยทยทยทยทยทXยทยทยท{{ยท0 โ”‚
0x0000000002677d50 0d000000 04080000 30aa4700 00000000 โ”‚ ยทยทยทยทยทยทยทยท0ยทGยทยทยทยทยท โ”‚
0x0000000002677d60 abababab abababab abababab abababab โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚
0x0000000002677d70 00000000 00000000 00000000 00000000 โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚
0x0000000002677d80 00000000 00000000 581cbfec 7b7b0437 โ”‚ ยทยทยทยทยทยทยทยทXยทยทยท{{ยท7 โ”‚
0x0000000002677d90 00000000 00000000 00ababab abababab โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚
0x0000000002677da0 abababab abababab ab000000 00000000 โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚
0x0000000002677db0 00000000 00000000 00000000 00000000 โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚
0x0000000002677dc0 00000000 00000000 7c1cbccb 7b7b0400 โ”‚ ยทยทยทยทยทยทยทยท|ยทยทยท{{ยทยท โ”‚
0x0000000002677dd0 b05f0201 00000000 e0200201 00000000 โ”‚ ยท_ยทยทยทยทยทยทยท ยทยทยทยทยทยท โ”‚
0x0000000002677de0 eefeeefe eefeeefe eefeeefe eefeeefe โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚
0x0000000002677df0 eefeeefe eefeeefe eefeeefe eefeeefe โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚
CPointer<T>
NativePtr
0x02677dd0
T = IntVar
The difference in CPointer and CVariable is subtle
โ€ข They both contain an address/reference to some data in memory
โ€ข The difference is similar to that between C++ references & C++ pointer
A CVariable facilitates reading and writing of typed data
โ€ข Without considering pointers
A CPointer exposes the concept of a pointer for programmatic use
โ€ข Passing around, dereferencing, operations etc.
CPointer & CVariable
Pointer parameters of C Functions are mapped to CValuesRef<T>
CValuesRef
fun sum(numbers: CValuesRef<IntVar>?, size: Int): Int
int sum(const int * numbers, int size)
This is designed to make passing Kotlin data to functions easier
We can create temporary copies of the data to be used only for the call
The data is copied to and lives in Kotlin space
โ€ข This copying can be very expensive
A CPointer extends from a CValuesRef so it can be passed in directly
CValuesRef
CPointer<T>
CValuesRef<T>
CValues<T>
CValuesRef
Kotlin Native
0x0000000002677d00 00000000 00000000 581cbfec 7a7b0430 โ”‚ ยทยทยทยทยทยทยทยทXยทยทยทz{ยท0 โ”‚
0x0000000002677d10 107d6702 00000000 587d6702 00000000 โ”‚ ยท}gยทยทยทยทยทX}gยทยทยทยทยท โ”‚
0x0000000002677d20 abababab abababab abababab abababab โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚
0x0000000002677d30 00000000 00000000 00000000 00000000 โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚
0x0000000002677d40 eefeeefe eefeeefe 581cbfec 7b7b0430 โ”‚ ยทยทยทยทยทยทยทยทXยทยทยท{{ยท0 โ”‚
0x0000000002677d50 0d000000 04080000 30aa4700 00000000 โ”‚ ยทยทยทยทยทยทยทยท0ยทGยทยทยทยทยท โ”‚
0x0000000002677d60 abababab abababab abababab abababab โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚
0x0000000002677d70 00000000 00000000 00000000 00000000 โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚
0x0000000002677d80 00000000 00000000 581cbfec 7b7b0437 โ”‚ ยทยทยทยทยทยทยทยทXยทยทยท{{ยท7 โ”‚
0x0000000002677d90 00000000 00000000 00ababab abababab โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚
0x0000000002677da0 abababab abababab ab000000 00000000 โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚
0x0000000002677db0 00000000 00000000 00000000 00000000 โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚
0x0000000002677dc0 00000000 00000000 7c1cbccb 7b7b0400 โ”‚ ยทยทยทยทยทยทยทยท|ยทยทยท{{ยทยท โ”‚
0x0000000002677dd0 b05f0201 00000000 e0200201 00000000 โ”‚ ยท_ยทยทยทยทยทยทยท ยทยทยทยทยทยท โ”‚
0x0000000002677de0 eefeeefe eefeeefe eefeeefe eefeeefe โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚
0x0000000002677df0 eefeeefe eefeeefe eefeeefe eefeeefe โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚
CPointer<T>
NativePtr
0x02677dd0
T = IntVar
CValue<T>
ByteArray at 0x0ff75012
eefeeefe eefeeefe 581cbfec 7b7b0430
0d000000 04080000 30aa4700 00000000
abababab abababab abababab abababab
...
A Kotlin functionโ€™s C type is a CFunction
It can be obtained by calling staticCFunction
It only works with unbound functions
โ€ข So instance method references will not work (as they capture the object)
Lambda and static function references are both supported
Passing Kotlin Functions into C
CPointed
NativePointed
CVariable CFunction
ยฉ Instil Software 2019
Multi-Threading
To avoid common pitfalls of multi-threading with shared mutable state,
Kotlin imposes restrictions on how data can be shared between threads
Only one thread may own mutable data
โ€ข Ownership can be transferred
Only immutable data or โ€˜frozenโ€™ data can be shared between threads
โ€ข Any writes to frozen data results in an โ€˜InvalidMutabilityExceptionโ€™
Constraints in Sharing Data
Shared Mutable
XOR
โŠ•
Only Frozen or Immutable data can be safely shared between threads
Singleton objects and enums are automatically frozen
Arbitrary objects can be frozen via the โ€˜freezeโ€™ method
Global variables can be marked with @SharedImmutable
Global variables can also be marked with @ThreadLocal
โ€ข In which case each thread gets its own copy of the data
Freezing
These constraints apply to Kotlin data
โ€ข Natively allocated data will not have these restrictions imposed
There are also atomic constructs which can be mutated
โ€ข AtomicInt
โ€ข AtomicDouble
โ€ข Etc
Obviously, if using these constructs then you have all the potential pitfalls
โ€ข Race conditions, deadlocks etc
Breaking the Rules
ยฉ Instil Software 2019
Coroutines
A good ecosystem is essential for rapid development
As a lot of Kotlin code is multi-platform by default, many libraries can be
consumed by Kotlin Native
โ€ข Sometimes only partially support
A good example of this is the coroutines library
Using Libraries
โ€œCoroutines are computer-program components
that generalize subroutines for non-preemptive
multitasking, by allowing multiple entry points
for suspending and resuming execution at
certain locations.โ€
Wikipedia
Coroutine
1 1 2 2 3 3 4 4 5 5 6 6 7 7
1
1
2
2
3
3
4
4
5
5
6
6
7
7
Consider 3 independent jobs of work
Event Loop with Asynchronous Blocks
Start 5 6EndBlocking Start 5 6EndBlocking Start 5 6EndBlocking
Start 5 6EndBlocking
Start 5 6EndBlocking
Start 5 6EndBlocking
If we want to run these in parallel we could create multiple threads
Asynchronous Use Case โ€“ Thread Pools
Start End
Blocking
Start End
Blocking
Start 5 6End
Blocking
Coroutines as Light Weight Threads
Start EndBlocking
Start EndBlocking
Start 5 6EndBlocking
Coroutines Scale
Start EndBlocking
Start EndBlocking
Start 5 6EndBlocking
Start EndBlocking
Start EndBlocking
Start 5 6EndBlocking
Start EndBlocking
ยฉ Instil Software 2019
โ€ข Objective C Interop
Swift Interop
Swift itself is not supported but Objective C is supported
Swift APIs can be exported to Objective C by annotating with @objc
Bidirectional interop with Objective C is more intuitive & complete than C
โ€ข Classes and interfaces/protocols can be used
โ€ข Reference counting and garbage collection are integrated
โ€ข More types are automatically mapped e.g. List
Objective C & Swift Interop
We will focus on the interop story with Swift rather than Objective C directly
โ€ข It is a more modern language and the obvious choice for new development
Since Swift is translated to Objective C, we immediately lose features
โ€ข Generics
โ€ข Tuples
โ€ข Enumerations defined in Swift without Int raw value type
โ€ข Structures defined in Swift
โ€ข Top-level functions and global variables defined in Swift
โ€ข Typealiases defined in Swift
โ€ข Swift-style variadics
โ€ข Nested types
โ€ข Curried functions
Objective C & Swift Interop
We can also compile Kotlin into Apple frameworks and libraries
Under this scenario we do not have support for,
โ€ข Suspend functions
โ€ข Inline classes
But many things map intuitively
Objective C & Swift Interop
Note that for elements to get translated, they must be,
โ€ข Annotated with @objc
โ€ข Public within a public class
Translations
@objc
public class Employee : NSObject {
@objc public let name: String
@objc public var age: Int
@objc public var salary: Double
public let noObjC = ""
@objc let notPublic = ""
open class Employee : NSObject {
@ObjCMethod("name", "@16@0:8")
external open fun name(): String
@ObjCMethod("age", "q16@0:8")
external open fun age(): NSInteger
@ObjCMethod("setAge:", "v24@0:8q16")
external open fun setAge(age: NSInteger): Unit
@ObjCMethod("salary", "d16@0:8")
external open fun salary(): Double
@ObjCMethod("setSalary:", "v24@0:8d16")
external open fun setSalary(salary: Double): Unit
// ...
Mappings
Kotlin Swift Objective-C
class class @interface
interface protocol @protocol
constructor/create Initializer Initializer
Property Property Property
Method Method Method
@Throws throws error:(NSError**)error
Extension Extension Category member
companion member <- Class method or property Class method or property
null nil nil
Singleton Singleton() [Singleton singleton]
Kotlin Swift Objective-C
Primitive type Primitive type / NSNumber
Unit return type Void void
String String NSString
String NSMutableString NSMutableString
List Array NSArray
MutableList NSMutableArray NSMutableArray
Set Set NSSet
MutableSet NSMutableSet NSMutableSet
Map Dictionary NSDictionary
MutableMap NSMutableDictionary NSMutableDictionary
Function type Function type Block pointer type
Mapping
Function types also have good support including closures
Note that primitive parameters will be boxed
Type differences may cause function reference issues
โ€ข E.g. Expecting an a Long parameter for an Int parameter
Function Types
@objc
public func filter(numbers: [Int], predicate: (Int) -> Bool) -> [Int]
external open fun filter(numbers: List<*>,
predicate: (NSInteger) -> Boolean): List<*>
Swift
Kotlin
ยฉ Instil Software 2019
Summary
C++ interop is not there, only via C
Swift interop is good but not fully there
โ€ข Since it is translating via Objective C
Build times are slow - especially when compared with modern languages
โ€ข E.g. Kotlin/Java on JVM, TypeScript, C#
The Bad
Still beta so there are some issues
โ€ข In Windows the IDE keeps locking the klib so I need to restart
โ€ข Autocomplete not in CLion for Gradle KTS
โ€ข Documentation incomplete or out of date
Encountered memory leak that I couldnโ€™t quite track down
The Bad
With C, you will need to switch between Strings and pointers to Byte
โ€ข It will depend on the usage case
โ€ข E.g. function calls, struct fields, function pointers
You miss some of the features of the Java Standard Library
โ€ข Posix give some cross platform features but โ€ฆ
โ€ข There are differences in the APIs across platforms
โ€ข They are not Kotlin first so the usage is clunky
Performance is not there
โ€ข Generally when compared with say a JVM implementation
โ€ข CValues can have severe performance impact
The Bad
The Kotlin language is excellent so using in more environments is good
The tooling around code authoring is excellent
โ€ข Though documentation and debugging is not there yet
Interop with C and Objective C is fairly good
โ€ข Especially Swift/Objective C with memory management, closures etc.
The potential for sharing code across platforms is appealing
The Good
Kotlin is spreading
โ€ข The right balance between simplicity and productivity
โ€ข Easy interoperation with Java
Kotlin/Native is very interesting
โ€ข Still beta but JetBrains are working hard
โ€ข Provides a solution for iOS support
Summary
A good set of libraries allows you to be productive
โ€ข Kotlin/Native doesnโ€™t have thatโ€ฆyet
โ€ข The interop and wrapping of other libraries will be key
โ€ข First class support of more Kotlin libraries will be key
Kotlin, soon to be the write once, run anywhere language
Summary
Wellโ€ฆ.maybe
Questions?

More Related Content

What's hot

Using the New Apache Flink Kubernetes Operator in a Production Deployment
Using the New Apache Flink Kubernetes Operator in a Production DeploymentUsing the New Apache Flink Kubernetes Operator in a Production Deployment
Using the New Apache Flink Kubernetes Operator in a Production DeploymentFlink Forward
ย 
Symfony in microservice architecture
Symfony in microservice architectureSymfony in microservice architecture
Symfony in microservice architectureDaniele D'Angeli
ย 
Cloud native development without the toil
Cloud native development without the toilCloud native development without the toil
Cloud native development without the toilAmbassador Labs
ย 
Kafka error handling patterns and best practices | Hemant Desale and Aruna Ka...
Kafka error handling patterns and best practices | Hemant Desale and Aruna Ka...Kafka error handling patterns and best practices | Hemant Desale and Aruna Ka...
Kafka error handling patterns and best practices | Hemant Desale and Aruna Ka...HostedbyConfluent
ย 
Building a data warehouse with Pentaho and Docker
Building a data warehouse with Pentaho and DockerBuilding a data warehouse with Pentaho and Docker
Building a data warehouse with Pentaho and DockerWellington Marinho
ย 
JSON SQL Injection and the Lessons Learned
JSON SQL Injection and the Lessons LearnedJSON SQL Injection and the Lessons Learned
JSON SQL Injection and the Lessons LearnedKazuho Oku
ย 
Agile Software Development Methodologies
Agile Software Development MethodologiesAgile Software Development Methodologies
Agile Software Development Methodologieselvinefendi
ย 
IBM SpaceX Capstone Project
IBM SpaceX Capstone ProjectIBM SpaceX Capstone Project
IBM SpaceX Capstone ProjectYousefElbayomi
ย 
CNIT 123 Ch 10: Hacking Web Servers
CNIT 123 Ch 10: Hacking Web ServersCNIT 123 Ch 10: Hacking Web Servers
CNIT 123 Ch 10: Hacking Web ServersSam Bowne
ย 
Introduction to Extreme Programming
Introduction to Extreme ProgrammingIntroduction to Extreme Programming
Introduction to Extreme ProgrammingNaresh Jain
ย 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and pythonChetan Giridhar
ย 
SREcon 2016 Performance Checklists for SREs
SREcon 2016 Performance Checklists for SREsSREcon 2016 Performance Checklists for SREs
SREcon 2016 Performance Checklists for SREsBrendan Gregg
ย 
IT Architect Profession
IT Architect ProfessionIT Architect Profession
IT Architect ProfessionNugroho Gito
ย 
Building a Data Pipeline using Apache Airflow (on AWS / GCP)
Building a Data Pipeline using Apache Airflow (on AWS / GCP)Building a Data Pipeline using Apache Airflow (on AWS / GCP)
Building a Data Pipeline using Apache Airflow (on AWS / GCP)Yohei Onishi
ย 
Sessions and cookies in php
Sessions and cookies in phpSessions and cookies in php
Sessions and cookies in phpPavan b
ย 
Automated Virtualized Testing (AVT) with Docker, Kubernetes, WireMock and Gat...
Automated Virtualized Testing (AVT) with Docker, Kubernetes, WireMock and Gat...Automated Virtualized Testing (AVT) with Docker, Kubernetes, WireMock and Gat...
Automated Virtualized Testing (AVT) with Docker, Kubernetes, WireMock and Gat...VMware Tanzu
ย 
USENIX Vault'19: Performance analysis in Linux storage stack with BPF
USENIX Vault'19: Performance analysis in Linux storage stack with BPFUSENIX Vault'19: Performance analysis in Linux storage stack with BPF
USENIX Vault'19: Performance analysis in Linux storage stack with BPFTaeung Song
ย 
Eland: A Python client for data analysis and exploration
Eland: A Python client for data analysis and explorationEland: A Python client for data analysis and exploration
Eland: A Python client for data analysis and explorationElasticsearch
ย 

What's hot (20)

Using the New Apache Flink Kubernetes Operator in a Production Deployment
Using the New Apache Flink Kubernetes Operator in a Production DeploymentUsing the New Apache Flink Kubernetes Operator in a Production Deployment
Using the New Apache Flink Kubernetes Operator in a Production Deployment
ย 
Symfony in microservice architecture
Symfony in microservice architectureSymfony in microservice architecture
Symfony in microservice architecture
ย 
Cloud native development without the toil
Cloud native development without the toilCloud native development without the toil
Cloud native development without the toil
ย 
Kafka error handling patterns and best practices | Hemant Desale and Aruna Ka...
Kafka error handling patterns and best practices | Hemant Desale and Aruna Ka...Kafka error handling patterns and best practices | Hemant Desale and Aruna Ka...
Kafka error handling patterns and best practices | Hemant Desale and Aruna Ka...
ย 
Building a data warehouse with Pentaho and Docker
Building a data warehouse with Pentaho and DockerBuilding a data warehouse with Pentaho and Docker
Building a data warehouse with Pentaho and Docker
ย 
JSON SQL Injection and the Lessons Learned
JSON SQL Injection and the Lessons LearnedJSON SQL Injection and the Lessons Learned
JSON SQL Injection and the Lessons Learned
ย 
Spring Boot
Spring BootSpring Boot
Spring Boot
ย 
Agile Software Development Methodologies
Agile Software Development MethodologiesAgile Software Development Methodologies
Agile Software Development Methodologies
ย 
IBM SpaceX Capstone Project
IBM SpaceX Capstone ProjectIBM SpaceX Capstone Project
IBM SpaceX Capstone Project
ย 
CNIT 123 Ch 10: Hacking Web Servers
CNIT 123 Ch 10: Hacking Web ServersCNIT 123 Ch 10: Hacking Web Servers
CNIT 123 Ch 10: Hacking Web Servers
ย 
Introduction to Extreme Programming
Introduction to Extreme ProgrammingIntroduction to Extreme Programming
Introduction to Extreme Programming
ย 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
ย 
SREcon 2016 Performance Checklists for SREs
SREcon 2016 Performance Checklists for SREsSREcon 2016 Performance Checklists for SREs
SREcon 2016 Performance Checklists for SREs
ย 
IT Architect Profession
IT Architect ProfessionIT Architect Profession
IT Architect Profession
ย 
Sql Injection Myths and Fallacies
Sql Injection Myths and FallaciesSql Injection Myths and Fallacies
Sql Injection Myths and Fallacies
ย 
Building a Data Pipeline using Apache Airflow (on AWS / GCP)
Building a Data Pipeline using Apache Airflow (on AWS / GCP)Building a Data Pipeline using Apache Airflow (on AWS / GCP)
Building a Data Pipeline using Apache Airflow (on AWS / GCP)
ย 
Sessions and cookies in php
Sessions and cookies in phpSessions and cookies in php
Sessions and cookies in php
ย 
Automated Virtualized Testing (AVT) with Docker, Kubernetes, WireMock and Gat...
Automated Virtualized Testing (AVT) with Docker, Kubernetes, WireMock and Gat...Automated Virtualized Testing (AVT) with Docker, Kubernetes, WireMock and Gat...
Automated Virtualized Testing (AVT) with Docker, Kubernetes, WireMock and Gat...
ย 
USENIX Vault'19: Performance analysis in Linux storage stack with BPF
USENIX Vault'19: Performance analysis in Linux storage stack with BPFUSENIX Vault'19: Performance analysis in Linux storage stack with BPF
USENIX Vault'19: Performance analysis in Linux storage stack with BPF
ย 
Eland: A Python client for data analysis and exploration
Eland: A Python client for data analysis and explorationEland: A Python client for data analysis and exploration
Eland: A Python client for data analysis and exploration
ย 

Similar to Kotlin Native - C / Swift Interop - ACCU Autmn 2019

Kotlin for all the Things
Kotlin for all the ThingsKotlin for all the Things
Kotlin for all the ThingsEamonn Boyle
ย 
Kotlin for Android - Goto Copenhagan 2019
Kotlin for Android - Goto Copenhagan 2019Kotlin for Android - Goto Copenhagan 2019
Kotlin for Android - Goto Copenhagan 2019Eamonn Boyle
ย 
Transitioning Android Teams Into Kotlin
Transitioning Android Teams Into KotlinTransitioning Android Teams Into Kotlin
Transitioning Android Teams Into KotlinGarth Gilmour
ย 
Programming with Kotlin
Programming with KotlinProgramming with Kotlin
Programming with KotlinDavid Gassner
ย 
Having Fun with Kotlin Android - DILo Surabaya
Having Fun with Kotlin Android - DILo SurabayaHaving Fun with Kotlin Android - DILo Surabaya
Having Fun with Kotlin Android - DILo SurabayaDILo Surabaya
ย 
Kotlin Language powerpoint show file
Kotlin Language powerpoint show fileKotlin Language powerpoint show file
Kotlin Language powerpoint show fileSaurabh Tripathi
ย 
Introduction to Kotlin for Android developers
Introduction to Kotlin for Android developersIntroduction to Kotlin for Android developers
Introduction to Kotlin for Android developersMohamed Wael
ย 
MOOC_PRESENTATION_KOTLIN[1].pptx
MOOC_PRESENTATION_KOTLIN[1].pptxMOOC_PRESENTATION_KOTLIN[1].pptx
MOOC_PRESENTATION_KOTLIN[1].pptxkamalkantmaurya1
ย 
Hello to Kotlin
Hello to KotlinHello to Kotlin
Hello to KotlinFatimaYousif11
ย 
Introduction to Koltin for Android Part I
Introduction to Koltin for Android Part I Introduction to Koltin for Android Part I
Introduction to Koltin for Android Part I Atif AbbAsi
ย 
Kotlin Presentation
Kotlin PresentationKotlin Presentation
Kotlin PresentationShayan Pourvatan
ย 
Dear Kotliners - Java Developers are Humans too
Dear Kotliners - Java Developers are Humans tooDear Kotliners - Java Developers are Humans too
Dear Kotliners - Java Developers are Humans tooVivek Chanddru
ย 
Getting Started With Kotlin
Getting Started With KotlinGetting Started With Kotlin
Getting Started With KotlinGaurav sharma
ย 
Kotlin what_you_need_to_know-converted event 4 with nigerians
Kotlin  what_you_need_to_know-converted event 4 with nigeriansKotlin  what_you_need_to_know-converted event 4 with nigerians
Kotlin what_you_need_to_know-converted event 4 with nigeriansjunaidhasan17
ย 
Kotlin for Android Developers - 1
Kotlin for Android Developers - 1Kotlin for Android Developers - 1
Kotlin for Android Developers - 1Mohamed Nabil, MSc.
ย 
Kotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRreadyKotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRreadyMobileAcademy
ย 
Android Application Development (1).pptx
Android Application Development (1).pptxAndroid Application Development (1).pptx
Android Application Development (1).pptxadityakale2110
ย 
Kotlin for Android devs
Kotlin for Android devsKotlin for Android devs
Kotlin for Android devsAdit Lal
ย 
Building Mobile Apps with Android
Building Mobile Apps with AndroidBuilding Mobile Apps with Android
Building Mobile Apps with AndroidKurt Renzo Acosta
ย 

Similar to Kotlin Native - C / Swift Interop - ACCU Autmn 2019 (20)

Kotlin for all the Things
Kotlin for all the ThingsKotlin for all the Things
Kotlin for all the Things
ย 
Kotlin for Android - Goto Copenhagan 2019
Kotlin for Android - Goto Copenhagan 2019Kotlin for Android - Goto Copenhagan 2019
Kotlin for Android - Goto Copenhagan 2019
ย 
Transitioning Android Teams Into Kotlin
Transitioning Android Teams Into KotlinTransitioning Android Teams Into Kotlin
Transitioning Android Teams Into Kotlin
ย 
Programming with Kotlin
Programming with KotlinProgramming with Kotlin
Programming with Kotlin
ย 
Having Fun with Kotlin Android - DILo Surabaya
Having Fun with Kotlin Android - DILo SurabayaHaving Fun with Kotlin Android - DILo Surabaya
Having Fun with Kotlin Android - DILo Surabaya
ย 
Kotlin Language powerpoint show file
Kotlin Language powerpoint show fileKotlin Language powerpoint show file
Kotlin Language powerpoint show file
ย 
Introduction to Kotlin for Android developers
Introduction to Kotlin for Android developersIntroduction to Kotlin for Android developers
Introduction to Kotlin for Android developers
ย 
MOOC_PRESENTATION_KOTLIN[1].pptx
MOOC_PRESENTATION_KOTLIN[1].pptxMOOC_PRESENTATION_KOTLIN[1].pptx
MOOC_PRESENTATION_KOTLIN[1].pptx
ย 
moocs_ppt.pptx
moocs_ppt.pptxmoocs_ppt.pptx
moocs_ppt.pptx
ย 
Hello to Kotlin
Hello to KotlinHello to Kotlin
Hello to Kotlin
ย 
Introduction to Koltin for Android Part I
Introduction to Koltin for Android Part I Introduction to Koltin for Android Part I
Introduction to Koltin for Android Part I
ย 
Kotlin Presentation
Kotlin PresentationKotlin Presentation
Kotlin Presentation
ย 
Dear Kotliners - Java Developers are Humans too
Dear Kotliners - Java Developers are Humans tooDear Kotliners - Java Developers are Humans too
Dear Kotliners - Java Developers are Humans too
ย 
Getting Started With Kotlin
Getting Started With KotlinGetting Started With Kotlin
Getting Started With Kotlin
ย 
Kotlin what_you_need_to_know-converted event 4 with nigerians
Kotlin  what_you_need_to_know-converted event 4 with nigeriansKotlin  what_you_need_to_know-converted event 4 with nigerians
Kotlin what_you_need_to_know-converted event 4 with nigerians
ย 
Kotlin for Android Developers - 1
Kotlin for Android Developers - 1Kotlin for Android Developers - 1
Kotlin for Android Developers - 1
ย 
Kotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRreadyKotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRready
ย 
Android Application Development (1).pptx
Android Application Development (1).pptxAndroid Application Development (1).pptx
Android Application Development (1).pptx
ย 
Kotlin for Android devs
Kotlin for Android devsKotlin for Android devs
Kotlin for Android devs
ย 
Building Mobile Apps with Android
Building Mobile Apps with AndroidBuilding Mobile Apps with Android
Building Mobile Apps with Android
ย 

More from Eamonn Boyle

2019-06 - Goto Amsterdam - Microservices
2019-06 - Goto Amsterdam - Microservices2019-06 - Goto Amsterdam - Microservices
2019-06 - Goto Amsterdam - MicroservicesEamonn Boyle
ย 
2019-01-29 - Demystifying Kotlin Coroutines
2019-01-29 - Demystifying Kotlin Coroutines2019-01-29 - Demystifying Kotlin Coroutines
2019-01-29 - Demystifying Kotlin CoroutinesEamonn Boyle
ย 
BelTech 2017 - Building Quality in the Browser
BelTech 2017 - Building Quality in the BrowserBelTech 2017 - Building Quality in the Browser
BelTech 2017 - Building Quality in the BrowserEamonn Boyle
ย 
ASP .Net Core SPA Templates
ASP .Net Core SPA TemplatesASP .Net Core SPA Templates
ASP .Net Core SPA TemplatesEamonn Boyle
ย 
Being Expressive in Code
Being Expressive in CodeBeing Expressive in Code
Being Expressive in CodeEamonn Boyle
ย 
2018-09 - F# and Fable
2018-09 - F# and Fable2018-09 - F# and Fable
2018-09 - F# and FableEamonn Boyle
ย 

More from Eamonn Boyle (6)

2019-06 - Goto Amsterdam - Microservices
2019-06 - Goto Amsterdam - Microservices2019-06 - Goto Amsterdam - Microservices
2019-06 - Goto Amsterdam - Microservices
ย 
2019-01-29 - Demystifying Kotlin Coroutines
2019-01-29 - Demystifying Kotlin Coroutines2019-01-29 - Demystifying Kotlin Coroutines
2019-01-29 - Demystifying Kotlin Coroutines
ย 
BelTech 2017 - Building Quality in the Browser
BelTech 2017 - Building Quality in the BrowserBelTech 2017 - Building Quality in the Browser
BelTech 2017 - Building Quality in the Browser
ย 
ASP .Net Core SPA Templates
ASP .Net Core SPA TemplatesASP .Net Core SPA Templates
ASP .Net Core SPA Templates
ย 
Being Expressive in Code
Being Expressive in CodeBeing Expressive in Code
Being Expressive in Code
ย 
2018-09 - F# and Fable
2018-09 - F# and Fable2018-09 - F# and Fable
2018-09 - F# and Fable
ย 

Recently uploaded

(Genuine) Escort Service Lucknow | Starting โ‚น,5K To @25k with A/C ๐Ÿง‘๐Ÿฝโ€โค๏ธโ€๐Ÿง‘๐Ÿป 89...
(Genuine) Escort Service Lucknow | Starting โ‚น,5K To @25k with A/C ๐Ÿง‘๐Ÿฝโ€โค๏ธโ€๐Ÿง‘๐Ÿป 89...(Genuine) Escort Service Lucknow | Starting โ‚น,5K To @25k with A/C ๐Ÿง‘๐Ÿฝโ€โค๏ธโ€๐Ÿง‘๐Ÿป 89...
(Genuine) Escort Service Lucknow | Starting โ‚น,5K To @25k with A/C ๐Ÿง‘๐Ÿฝโ€โค๏ธโ€๐Ÿง‘๐Ÿป 89...gurkirankumar98700
ย 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
ย 
Call Girls In Mukherjee Nagar ๐Ÿ“ฑ 9999965857 ๐Ÿคฉ Delhi ๐Ÿซฆ HOT AND SEXY VVIP ๐ŸŽ SE...
Call Girls In Mukherjee Nagar ๐Ÿ“ฑ  9999965857  ๐Ÿคฉ Delhi ๐Ÿซฆ HOT AND SEXY VVIP ๐ŸŽ SE...Call Girls In Mukherjee Nagar ๐Ÿ“ฑ  9999965857  ๐Ÿคฉ Delhi ๐Ÿซฆ HOT AND SEXY VVIP ๐ŸŽ SE...
Call Girls In Mukherjee Nagar ๐Ÿ“ฑ 9999965857 ๐Ÿคฉ Delhi ๐Ÿซฆ HOT AND SEXY VVIP ๐ŸŽ SE...Call Girls In Delhi Whatsup 9873940964 Enjoy Unlimited Pleasure
ย 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
ย 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
ย 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
ย 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
ย 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
ย 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
ย 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
ย 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
ย 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto Gonzรกlez Trastoy
ย 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
ย 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
ย 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
ย 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
ย 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
ย 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
ย 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
ย 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
ย 

Recently uploaded (20)

(Genuine) Escort Service Lucknow | Starting โ‚น,5K To @25k with A/C ๐Ÿง‘๐Ÿฝโ€โค๏ธโ€๐Ÿง‘๐Ÿป 89...
(Genuine) Escort Service Lucknow | Starting โ‚น,5K To @25k with A/C ๐Ÿง‘๐Ÿฝโ€โค๏ธโ€๐Ÿง‘๐Ÿป 89...(Genuine) Escort Service Lucknow | Starting โ‚น,5K To @25k with A/C ๐Ÿง‘๐Ÿฝโ€โค๏ธโ€๐Ÿง‘๐Ÿป 89...
(Genuine) Escort Service Lucknow | Starting โ‚น,5K To @25k with A/C ๐Ÿง‘๐Ÿฝโ€โค๏ธโ€๐Ÿง‘๐Ÿป 89...
ย 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
ย 
Call Girls In Mukherjee Nagar ๐Ÿ“ฑ 9999965857 ๐Ÿคฉ Delhi ๐Ÿซฆ HOT AND SEXY VVIP ๐ŸŽ SE...
Call Girls In Mukherjee Nagar ๐Ÿ“ฑ  9999965857  ๐Ÿคฉ Delhi ๐Ÿซฆ HOT AND SEXY VVIP ๐ŸŽ SE...Call Girls In Mukherjee Nagar ๐Ÿ“ฑ  9999965857  ๐Ÿคฉ Delhi ๐Ÿซฆ HOT AND SEXY VVIP ๐ŸŽ SE...
Call Girls In Mukherjee Nagar ๐Ÿ“ฑ 9999965857 ๐Ÿคฉ Delhi ๐Ÿซฆ HOT AND SEXY VVIP ๐ŸŽ SE...
ย 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
ย 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
ย 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
ย 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
ย 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
ย 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
ย 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
ย 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
ย 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
ย 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
ย 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
ย 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
ย 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
ย 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
ย 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
ย 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
ย 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
ย 

Kotlin Native - C / Swift Interop - ACCU Autmn 2019

  • 1. training@instil.co ACCU - November 2019 ยฉ Instil Software 2019 Interop Between Kotlin Native and C / Swift The Good, the Bad and the Ugly @BoyleEamonn Eamonn Boyle @GarthGilmour Garth Gilmour
  • 2. Me
  • 3. Him
  • 4. Us
  • 6.
  • 7. 2010: Work begins on Kotlin within JetBrains 2011: First public announcement on Kotlin 2012: Open sourced under Apache 2 license 2016: Version one released 2017: First class support on Android 2018: Version 1.3 released A Kotlin Timeline
  • 8. Weโ€™ve bought into Kotlin in a big way Kotlinโ€ฆOkโ€ฆweโ€™re obsessed
  • 9. We held a workshop at the conference โ€ข React App with Kotlin on Server & Browser Kotlinโ€ฆOkโ€ฆweโ€™re obsessed
  • 10. Weโ€™re going back againโ€ฆ
  • 11. If youโ€™re working on the Java Virtual Machine, try not to use Java Having done C# for many years I was so happy to see Kotlin for the JVM Problems with Java โ€ข Verbose, Verbose, Verbose, Verbose, Verbose, Verbose, Verbose, Verbose, โ€ข Nulls โ€ข Completely OO Why Kotlin - Java โ€“ Yuck!
  • 12. No need to wait - the interop story is so good โ€ข Call into all that legacy Java code easily โ€ข Call into your new Kotlin code from Java easily Really concise, yet clear syntax โ€ข Less is more โ€ข โ€œBorrowsโ€ the best bits of other languages โ€ข Less baggage Why Kotlin โ€“ So Much to Like Null Safety String Templates Default parameters Extensions Free Functions Coroutines Single Expression Functions Reified generics Data classes and Properties Type Inference Smart Casts Operator overloading
  • 13. Basic Model Classes โ€“ Java public class Movie { private String title; private String description; private Rating rating; private Genre genre; }
  • 14. Basic Model Classes โ€“ Java public class Movie { private String title; private String description; private Rating rating; private Genre genre; public Movie(String title, String description, Rating rating, Genre genre) { this.title = title; this.description = description; this.rating = rating; this.genre = genre; } }
  • 15. Basic Model Classes โ€“ Java public class Movie { private String title; private String description; private Rating rating; private Genre genre; public Movie(String title, String description, Rating rating, Genre genre) { this.title = title; this.description = description; this.rating = rating; this.genre = genre; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; }
  • 16. Basic Model Classes โ€“ Java public class Movie { private String title; private String description; private Rating rating; private Genre genre; public Movie(String title, String description, Rating rating, Genre genre) { this.title = title; this.description = description; this.rating = rating; this.genre = genre; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Rating getRating() { return rating; } public void setRating(Rating rating) { this.rating = rating; } public Genre getGenre() { return genre; } public void setGenre(Genre genre) { this.genre = genre; } }
  • 17. Basic Model Classes โ€“ Java vs Kotlin public class Movie { private String title; private String description; private Rating rating; private Genre genre; public Movie(String title, String description, Rating rating, Genre genre) { this.title = title; this.description = description; this.rating = rating; this.genre = genre; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Rating getRating() { return rating; } public void setRating(Rating rating) { this.rating = rating; } public Genre getGenre() { return genre; } public void setGenre(Genre genre) { this.genre = genre; } } data class Movie(var title: String, var description: String, var rating: Rating, var genre: Genre) { } Java Kotlin
  • 18. Basic Model Classes โ€“ Java vs Kotlin import java.util.Objects; public class Movie { private String title; private String description; private Rating rating; private Genre genre; public Movie(String title, String description, Rating rating, Genre genre) { this.title = title; this.description = description; this.rating = rating; this.genre = genre; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Rating getRating() { return rating; } public void setRating(Rating rating) { this.rating = rating; } public Genre getGenre() { return genre; } public void setGenre(Genre genre) { this.genre = genre; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Movie movie = (Movie) o; return Objects.equals(title, movie.title) && Objects.equals(description, movie.description) && Objects.equals(rating, movie.rating) && Objects.equals(genre, movie.genre); } @Override public int hashCode() { return Objects.hash(title, description, rating, genre); } @Override public String toString() { return "Movie{" + "title='" + title + ''' + ", description='" + description + ''' + ", rating=" + rating + ", genre=" + genre + '}'; } } data class Movie(var title: String, var description: String, var rating: Rating, var genre: Genre) { } We also get hashCode(), equals(), toString() and moreโ€ฆ External libraries and tools like Lombok will help with Java Java Kotlin
  • 19.
  • 20. Null Safety private fun processUserPolicy(user: User) { val policy = user.policy if (policy.isComplete) { policyProcessor.process(policy) } } private static void processUserPolicy(User user) { if (user != null && user.getPolicy() != null) { Policy policy = user.getPolicy(); if (policy.isComplete()) { policyProcessor.process(policy); } } } Java Kotlin
  • 21. Functional Chaining โ€“ vs Java Reified Generics with a single primitive representation makes the code simpler double averageSalary = employees .stream() .filter(x -> x.getDepartment() == Engineering) .mapToInt(Employee::getSalary) .average() .orElse(0); Java val averageSalary = employees .filter { it.department === Engineering } .map { it.salary } .average() Kotlin
  • 22. Kotlin was originally for writing server and desktop Java โ€ข Thatโ€™s what JetBrains were building themselves This evolved further into supporting Android โ€ข Which is now what itโ€™s very popular for JetBrains went further to support the Browser in Kotlin/JS and native in Kotlin.Native Kotlin Platforms
  • 23. Kotlin/Native is a technology for compiling Kotlin code to native binaries โ€ข It runs without a virtual machine โ€ข The output is NOT portable Although the binary output is not portable, the source IS portable โ€ข The compiler can compile the same source to multiple outputs/platforms โ€ข The source can be placed into a multiplatform project and used for JVM, JS etc Kotlin Native Kotlin Compiler LLVMSource Native Binary LLVM IR
  • 24. Supported platforms include, โ€ข iOS (arm32, arm64, emulator x86_64) โ€ข MacOS (x86_64) โ€ข Android (arm32, arm64) โ€ข Windows (mingw x86_64) โ€ข Linux (x86_64, arm32, MIPS, MIPS little endian, Raspberry Pi) โ€ข WebAssembly (wasm32) We can link to or dynamically call into other native libraries โ€ข C, Swift or ObjectiveC libraries Note โ€“ Kotlin/Native is still beta Kotlin Native
  • 25. Scenarios Kotlin Native Executable Kotlin Native Library Platform Native Executable Kotlin Native Executable Platform Native Library Multiplatform Project Executable or Library Multiple Targets in One Project Common Code Platform Specific Code iOS Android
  • 26. You can drive everything from the command line โ€ข Kotlin Native CLI tools โ€ข Gradle for fully builder system An IDE can make the whole experience much easier IDEs
  • 27. Common JVM APIs such as kotlin.io arenโ€™t available But there are multi-platform and native libraries that you can consume Kotlin Native also supports excellent interop with C and ObjectiveC/Swift API compatibility shown on doc pages Supported APIs import kotlinx.io.* import kotlinx.cinterop.*
  • 28. To simplify things further, common native APIs have already been wrapped These bindings are platform specific but include โ€ข Posix โ€ข zlib โ€ข GDI (Windows) โ€ข OpenGL โ€ข Apple Frameworks Platform Libraries import platform.posix.*
  • 29. A major reason for choosing Kotlin is that it is a great language For Kotlin Native, the language remains unchanged โ€ข Though the implementation and runtime is wildly different In native, it uses reference counting for automated memory management โ€ข And an additional cyclical garbage collector Advantages of the Kotlin Language
  • 30. Letโ€™s have a look at native features and along the way see some nice features of the language generally Advantages of the Kotlin Language
  • 31. ยฉ Instil Software 2019 โ€ข Kotlin Native Examples Demo
  • 34. Data can be copied back and forth between Kotlin and C โ€ข Kotlin Native can automatically marshal from C primitive types Primitive Types C Kotlin char kotlin.Byte unsigned char kotlin.UByte short kotlin.Short unsigned short kotlin.UShort int kotlin.Int unsigned int kotlin.UInt long long kotlin.Long unsigned long long kotlin.ULong float kotlin.Float double kotlin.Double
  • 35. If directly referencing C data, Kotlin Native uses a CVariable type Internally, it contains a reference to C data via a NativePtr type โ€ข You can think of it a little like a wrapper or C++ reference or lvalue CVariable CVariable NativePtr 0x02677dd0 Kotlin Native 0x0000000002677d00 00000000 00000000 581cbfec 7a7b0430 โ”‚ ยทยทยทยทยทยทยทยทXยทยทยทz{ยท0 โ”‚ 0x0000000002677d10 107d6702 00000000 587d6702 00000000 โ”‚ ยท}gยทยทยทยทยทX}gยทยทยทยทยท โ”‚ 0x0000000002677d20 abababab abababab abababab abababab โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚ 0x0000000002677d30 00000000 00000000 00000000 00000000 โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚ 0x0000000002677d40 eefeeefe eefeeefe 581cbfec 7b7b0430 โ”‚ ยทยทยทยทยทยทยทยทXยทยทยท{{ยท0 โ”‚ 0x0000000002677d50 0d000000 04080000 30aa4700 00000000 โ”‚ ยทยทยทยทยทยทยทยท0ยทGยทยทยทยทยท โ”‚ 0x0000000002677d60 abababab abababab abababab abababab โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚ 0x0000000002677d70 00000000 00000000 00000000 00000000 โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚ 0x0000000002677d80 00000000 00000000 581cbfec 7b7b0437 โ”‚ ยทยทยทยทยทยทยทยทXยทยทยท{{ยท7 โ”‚ 0x0000000002677d90 00000000 00000000 00ababab abababab โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚ 0x0000000002677da0 abababab abababab ab000000 00000000 โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚ 0x0000000002677db0 00000000 00000000 00000000 00000000 โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚ 0x0000000002677dc0 00000000 00000000 7c1cbccb 7b7b0400 โ”‚ ยทยทยทยทยทยทยทยท|ยทยทยท{{ยทยท โ”‚ 0x0000000002677dd0 b05f0201 00000000 e0200201 00000000 โ”‚ ยท_ยทยทยทยทยทยทยท ยทยทยทยทยทยท โ”‚ 0x0000000002677de0 eefeeefe eefeeefe eefeeefe eefeeefe โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚ 0x0000000002677df0 eefeeefe eefeeefe eefeeefe eefeeefe โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚
  • 36. There are CVariable types for, โ€ข All the primitives - IntVar, DoubleVar etc โ€ข Enums โ€“ CEnumVar<T> โ€ข Structs โ€“ CStructVar<T> โ€ข Pointers (more on this later) โ€“ CPointerVar<T> CVariables allow reading and writing via the value property CVariable Types fun sum(total: IntVar, current: Int) { total.value += current }
  • 38. Structs can be easily created in C and mapped to Kotlin โ€ข The mapping is done automatically by including headers in the def file Structs class Employee(rawPtr: NativePtr) : CStructVar(rawPtr) { companion object : Type(24, 8) var name: CPointer<ByteVar>? get() = memberAt<CPointerVar<ByteVar>>(0).value set(value) { memberAt<CPointerVar<ByteVar>>(0).value = value } var age: Int get() = memberAt<IntVar>(8).value set(value) { memberAt<IntVar>(8).value = value } var salary: Double get() = memberAt<DoubleVar>(16).value set(value) { memberAt<DoubleVar>(16).value = value } } typedef struct { char* name; int age; double salary; } Employee;
  • 39. The type name matches the C typedef but it is a CStructVar Structs โ€“ Points to Note class Employee(rawPtr: NativePtr) : CStructVar(rawPtr) { companion object : Type(24, 8) ... } typedef struct { char* name; int age; double salary; } Employee;
  • 40. Internally it uses addresses to get CVariables but marshals into Kotlin types Structs โ€“ Points to Note class Employee(rawPtr: NativePtr) : CStructVar(rawPtr) { ... var age: Int get() = memberAt<IntVar>(8).value set(value) { memberAt<IntVar>(8).value = value } var salary: Double get() = memberAt<DoubleVar>(16).value set(value) { memberAt<DoubleVar>(16).value = value } } typedef struct { char* name; int age; double salary; } Employee;
  • 41. Except where the returned type is a C type โ€ข E.g. pointers Structs โ€“ Points to Note class Employee(rawPtr: NativePtr) : CStructVar(rawPtr) { var name: CPointer<ByteVar>? get() = memberAt<CPointerVar<ByteVar>>(0).value set(value) { memberAt<CPointerVar<ByteVar>>(0).value = value } ... } typedef struct { char* name; int age; double salary; } Employee;
  • 42. You will note that structs have a Type that includes size and alignment info This facilitates allocation Allocating Structs class Employee(rawPtr: NativePtr) : CStructVar(rawPtr) { companion object : Type(24, 8) ... } typedef struct { char* name; int age; double salary; } Employee;
  • 44. As well as CVariables, Kotlin Native supports pointers via CPointer<T> The type of data pointed to, T, must be a CVariable type โ€ข Itโ€™s actually CPointed which can be a CFunction, but more on that later Pointers Kotlin Native 0x0000000002677d00 00000000 00000000 581cbfec 7a7b0430 โ”‚ ยทยทยทยทยทยทยทยทXยทยทยทz{ยท0 โ”‚ 0x0000000002677d10 107d6702 00000000 587d6702 00000000 โ”‚ ยท}gยทยทยทยทยทX}gยทยทยทยทยท โ”‚ 0x0000000002677d20 abababab abababab abababab abababab โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚ 0x0000000002677d30 00000000 00000000 00000000 00000000 โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚ 0x0000000002677d40 eefeeefe eefeeefe 581cbfec 7b7b0430 โ”‚ ยทยทยทยทยทยทยทยทXยทยทยท{{ยท0 โ”‚ 0x0000000002677d50 0d000000 04080000 30aa4700 00000000 โ”‚ ยทยทยทยทยทยทยทยท0ยทGยทยทยทยทยท โ”‚ 0x0000000002677d60 abababab abababab abababab abababab โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚ 0x0000000002677d70 00000000 00000000 00000000 00000000 โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚ 0x0000000002677d80 00000000 00000000 581cbfec 7b7b0437 โ”‚ ยทยทยทยทยทยทยทยทXยทยทยท{{ยท7 โ”‚ 0x0000000002677d90 00000000 00000000 00ababab abababab โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚ 0x0000000002677da0 abababab abababab ab000000 00000000 โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚ 0x0000000002677db0 00000000 00000000 00000000 00000000 โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚ 0x0000000002677dc0 00000000 00000000 7c1cbccb 7b7b0400 โ”‚ ยทยทยทยทยทยทยทยท|ยทยทยท{{ยทยท โ”‚ 0x0000000002677dd0 b05f0201 00000000 e0200201 00000000 โ”‚ ยท_ยทยทยทยทยทยทยท ยทยทยทยทยทยท โ”‚ 0x0000000002677de0 eefeeefe eefeeefe eefeeefe eefeeefe โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚ 0x0000000002677df0 eefeeefe eefeeefe eefeeefe eefeeefe โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚ CPointer<T> NativePtr 0x02677dd0 T = IntVar
  • 45. The difference in CPointer and CVariable is subtle โ€ข They both contain an address/reference to some data in memory โ€ข The difference is similar to that between C++ references & C++ pointer A CVariable facilitates reading and writing of typed data โ€ข Without considering pointers A CPointer exposes the concept of a pointer for programmatic use โ€ข Passing around, dereferencing, operations etc. CPointer & CVariable
  • 46. Pointer parameters of C Functions are mapped to CValuesRef<T> CValuesRef fun sum(numbers: CValuesRef<IntVar>?, size: Int): Int int sum(const int * numbers, int size)
  • 47. This is designed to make passing Kotlin data to functions easier We can create temporary copies of the data to be used only for the call The data is copied to and lives in Kotlin space โ€ข This copying can be very expensive A CPointer extends from a CValuesRef so it can be passed in directly CValuesRef CPointer<T> CValuesRef<T> CValues<T>
  • 48. CValuesRef Kotlin Native 0x0000000002677d00 00000000 00000000 581cbfec 7a7b0430 โ”‚ ยทยทยทยทยทยทยทยทXยทยทยทz{ยท0 โ”‚ 0x0000000002677d10 107d6702 00000000 587d6702 00000000 โ”‚ ยท}gยทยทยทยทยทX}gยทยทยทยทยท โ”‚ 0x0000000002677d20 abababab abababab abababab abababab โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚ 0x0000000002677d30 00000000 00000000 00000000 00000000 โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚ 0x0000000002677d40 eefeeefe eefeeefe 581cbfec 7b7b0430 โ”‚ ยทยทยทยทยทยทยทยทXยทยทยท{{ยท0 โ”‚ 0x0000000002677d50 0d000000 04080000 30aa4700 00000000 โ”‚ ยทยทยทยทยทยทยทยท0ยทGยทยทยทยทยท โ”‚ 0x0000000002677d60 abababab abababab abababab abababab โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚ 0x0000000002677d70 00000000 00000000 00000000 00000000 โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚ 0x0000000002677d80 00000000 00000000 581cbfec 7b7b0437 โ”‚ ยทยทยทยทยทยทยทยทXยทยทยท{{ยท7 โ”‚ 0x0000000002677d90 00000000 00000000 00ababab abababab โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚ 0x0000000002677da0 abababab abababab ab000000 00000000 โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚ 0x0000000002677db0 00000000 00000000 00000000 00000000 โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚ 0x0000000002677dc0 00000000 00000000 7c1cbccb 7b7b0400 โ”‚ ยทยทยทยทยทยทยทยท|ยทยทยท{{ยทยท โ”‚ 0x0000000002677dd0 b05f0201 00000000 e0200201 00000000 โ”‚ ยท_ยทยทยทยทยทยทยท ยทยทยทยทยทยท โ”‚ 0x0000000002677de0 eefeeefe eefeeefe eefeeefe eefeeefe โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚ 0x0000000002677df0 eefeeefe eefeeefe eefeeefe eefeeefe โ”‚ ยทยทยทยทยทยทยทยทยทยทยทยทยทยทยทยท โ”‚ CPointer<T> NativePtr 0x02677dd0 T = IntVar CValue<T> ByteArray at 0x0ff75012 eefeeefe eefeeefe 581cbfec 7b7b0430 0d000000 04080000 30aa4700 00000000 abababab abababab abababab abababab ...
  • 49. A Kotlin functionโ€™s C type is a CFunction It can be obtained by calling staticCFunction It only works with unbound functions โ€ข So instance method references will not work (as they capture the object) Lambda and static function references are both supported Passing Kotlin Functions into C CPointed NativePointed CVariable CFunction
  • 50. ยฉ Instil Software 2019 Multi-Threading
  • 51. To avoid common pitfalls of multi-threading with shared mutable state, Kotlin imposes restrictions on how data can be shared between threads Only one thread may own mutable data โ€ข Ownership can be transferred Only immutable data or โ€˜frozenโ€™ data can be shared between threads โ€ข Any writes to frozen data results in an โ€˜InvalidMutabilityExceptionโ€™ Constraints in Sharing Data Shared Mutable XOR โŠ•
  • 52. Only Frozen or Immutable data can be safely shared between threads Singleton objects and enums are automatically frozen Arbitrary objects can be frozen via the โ€˜freezeโ€™ method Global variables can be marked with @SharedImmutable Global variables can also be marked with @ThreadLocal โ€ข In which case each thread gets its own copy of the data Freezing
  • 53. These constraints apply to Kotlin data โ€ข Natively allocated data will not have these restrictions imposed There are also atomic constructs which can be mutated โ€ข AtomicInt โ€ข AtomicDouble โ€ข Etc Obviously, if using these constructs then you have all the potential pitfalls โ€ข Race conditions, deadlocks etc Breaking the Rules
  • 54. ยฉ Instil Software 2019 Coroutines
  • 55. A good ecosystem is essential for rapid development As a lot of Kotlin code is multi-platform by default, many libraries can be consumed by Kotlin Native โ€ข Sometimes only partially support A good example of this is the coroutines library Using Libraries
  • 56. โ€œCoroutines are computer-program components that generalize subroutines for non-preemptive multitasking, by allowing multiple entry points for suspending and resuming execution at certain locations.โ€ Wikipedia Coroutine
  • 57. 1 1 2 2 3 3 4 4 5 5 6 6 7 7
  • 59. Consider 3 independent jobs of work Event Loop with Asynchronous Blocks Start 5 6EndBlocking Start 5 6EndBlocking Start 5 6EndBlocking Start 5 6EndBlocking Start 5 6EndBlocking Start 5 6EndBlocking If we want to run these in parallel we could create multiple threads
  • 60. Asynchronous Use Case โ€“ Thread Pools Start End Blocking Start End Blocking Start 5 6End Blocking
  • 61. Coroutines as Light Weight Threads Start EndBlocking Start EndBlocking Start 5 6EndBlocking
  • 62. Coroutines Scale Start EndBlocking Start EndBlocking Start 5 6EndBlocking Start EndBlocking Start EndBlocking Start 5 6EndBlocking Start EndBlocking
  • 63. ยฉ Instil Software 2019 โ€ข Objective C Interop Swift Interop
  • 64. Swift itself is not supported but Objective C is supported Swift APIs can be exported to Objective C by annotating with @objc Bidirectional interop with Objective C is more intuitive & complete than C โ€ข Classes and interfaces/protocols can be used โ€ข Reference counting and garbage collection are integrated โ€ข More types are automatically mapped e.g. List Objective C & Swift Interop
  • 65. We will focus on the interop story with Swift rather than Objective C directly โ€ข It is a more modern language and the obvious choice for new development Since Swift is translated to Objective C, we immediately lose features โ€ข Generics โ€ข Tuples โ€ข Enumerations defined in Swift without Int raw value type โ€ข Structures defined in Swift โ€ข Top-level functions and global variables defined in Swift โ€ข Typealiases defined in Swift โ€ข Swift-style variadics โ€ข Nested types โ€ข Curried functions Objective C & Swift Interop
  • 66. We can also compile Kotlin into Apple frameworks and libraries Under this scenario we do not have support for, โ€ข Suspend functions โ€ข Inline classes But many things map intuitively Objective C & Swift Interop
  • 67. Note that for elements to get translated, they must be, โ€ข Annotated with @objc โ€ข Public within a public class Translations @objc public class Employee : NSObject { @objc public let name: String @objc public var age: Int @objc public var salary: Double public let noObjC = "" @objc let notPublic = "" open class Employee : NSObject { @ObjCMethod("name", "@16@0:8") external open fun name(): String @ObjCMethod("age", "q16@0:8") external open fun age(): NSInteger @ObjCMethod("setAge:", "v24@0:8q16") external open fun setAge(age: NSInteger): Unit @ObjCMethod("salary", "d16@0:8") external open fun salary(): Double @ObjCMethod("setSalary:", "v24@0:8d16") external open fun setSalary(salary: Double): Unit // ...
  • 68. Mappings Kotlin Swift Objective-C class class @interface interface protocol @protocol constructor/create Initializer Initializer Property Property Property Method Method Method @Throws throws error:(NSError**)error Extension Extension Category member companion member <- Class method or property Class method or property null nil nil Singleton Singleton() [Singleton singleton]
  • 69. Kotlin Swift Objective-C Primitive type Primitive type / NSNumber Unit return type Void void String String NSString String NSMutableString NSMutableString List Array NSArray MutableList NSMutableArray NSMutableArray Set Set NSSet MutableSet NSMutableSet NSMutableSet Map Dictionary NSDictionary MutableMap NSMutableDictionary NSMutableDictionary Function type Function type Block pointer type Mapping
  • 70. Function types also have good support including closures Note that primitive parameters will be boxed Type differences may cause function reference issues โ€ข E.g. Expecting an a Long parameter for an Int parameter Function Types @objc public func filter(numbers: [Int], predicate: (Int) -> Bool) -> [Int] external open fun filter(numbers: List<*>, predicate: (NSInteger) -> Boolean): List<*> Swift Kotlin
  • 71. ยฉ Instil Software 2019 Summary
  • 72. C++ interop is not there, only via C Swift interop is good but not fully there โ€ข Since it is translating via Objective C Build times are slow - especially when compared with modern languages โ€ข E.g. Kotlin/Java on JVM, TypeScript, C# The Bad
  • 73. Still beta so there are some issues โ€ข In Windows the IDE keeps locking the klib so I need to restart โ€ข Autocomplete not in CLion for Gradle KTS โ€ข Documentation incomplete or out of date Encountered memory leak that I couldnโ€™t quite track down The Bad
  • 74. With C, you will need to switch between Strings and pointers to Byte โ€ข It will depend on the usage case โ€ข E.g. function calls, struct fields, function pointers You miss some of the features of the Java Standard Library โ€ข Posix give some cross platform features but โ€ฆ โ€ข There are differences in the APIs across platforms โ€ข They are not Kotlin first so the usage is clunky Performance is not there โ€ข Generally when compared with say a JVM implementation โ€ข CValues can have severe performance impact The Bad
  • 75. The Kotlin language is excellent so using in more environments is good The tooling around code authoring is excellent โ€ข Though documentation and debugging is not there yet Interop with C and Objective C is fairly good โ€ข Especially Swift/Objective C with memory management, closures etc. The potential for sharing code across platforms is appealing The Good
  • 76. Kotlin is spreading โ€ข The right balance between simplicity and productivity โ€ข Easy interoperation with Java Kotlin/Native is very interesting โ€ข Still beta but JetBrains are working hard โ€ข Provides a solution for iOS support Summary
  • 77. A good set of libraries allows you to be productive โ€ข Kotlin/Native doesnโ€™t have thatโ€ฆyet โ€ข The interop and wrapping of other libraries will be key โ€ข First class support of more Kotlin libraries will be key Kotlin, soon to be the write once, run anywhere language Summary Wellโ€ฆ.maybe

Editor's Notes

  1. If the pools are created then dispatch time is faster