"Kotin Minimalist Tutorial" Chapter 16 Using Kotlin Native

Chapter 16 Using Kotlin Native

I have to say that JetBrains is a pragmatic company. The various IDEs are full of praise, and they are quite slippery to use. Similarly, Kotlin, born from JetBrains, is also a pragmatic programming language. Kotlin takes engineering practicality as the orientation and fully draws on the essence of Java, Scala, Groovy, C#, Gosu, JavaScript, Swift and other languages. Let us write The code can be described as quite elegant but without losing the quality and efficiency of the project. Kotlin Native can directly compile Kotlin code into machine code, which means it stands at the same level as C/C++, Go and Rust, so another competitor is added in this field.

In all the previous chapters, the Kotlin we used is based on the JVM operating environment. In this chapter, we will leave the JVM operating environment and move towards the ecosystem of system programming that directly compiles and generates native machine code: Kotlin Native.

16.1 Introduction to Kotlin Native

Kotlin Native uses LLVM to compile to machine code. Kotlin Native is mainly based on LLVM backend compiler (Backend Compiler) to generate native machine code.

Kotlin Native is designed to support programming in non-JVM virtual machine platform environments, such as ios and embedded platforms. It also supports interoperability with C.

16.1.1 LLVM

LLVM was originally the abbreviation of Low Level Virtual Machine. It is positioned as a virtual machine, but it is a relatively low-level virtual machine. LLVM is a framework system that builds a compiler (compiler), written in C++, and is used to optimize the compile-time, link-time, and run-time of programs written in any programming language. time) and idle-time, which are open to developers and compatible with existing scripts.

The emergence of LLVM is to solve the problem of compiler code reuse. When LLVM came up from a relatively high angle, it developed LLVM IR, an intermediate code representation language. LLVM IR fully considers various application scenarios, such as calling LLVM in the IDE for real-time code syntax checking, compiling and optimizing static and dynamic languages.

16.1.2 Support Platform

Kotlin Native now supports the following platforms:

Platform name target configuration
Linux linux
Mac OS macbook
Windows mingw
Android arm32 android_arm32
Android arm64 android_arm64
iOS iphone
Raspberry Pi raspberrypi

This means we can start the experience happily on these platforms! The latest pre-release version of Kotlin Native that has been released is v0.3.

16.1.3 Interpreted and compiled languages

Compiled language is a separate compilation process before the program is executed, and the program is translated into machine language. When the program is executed later, there is no need for translation. For example, C/C++, etc. are all compiled languages.

An interpreted language translates a program into machine language when it is running, so the running speed is slower than that of a compiled language. For example, Java, C#, etc. are all interpreted languages.

Although a Java program also has a compilation process before it runs, it is not compiled into machine language, but into bytecode (which can be understood as an intermediate language). At runtime, the JVM translates the bytecode into machine language.

16.2 Quick start Hello World

16.2.1 Preparing the operating environment

We go directly to Github to download the kotlin-native compiler package. The download address is: https://github.com/JetBrains/kotlin-native/releases.

Screenshot 2017-07-29 13.23.30.png

After downloading and decompressing, we can see the directory of Kotlin Native compiler konan as follows:

-rw-r--r--@  1 jack  staff   6828  6 20 22:47 GRADLE_PLUGIN.md
-rw-r--r--@  1 jack  staff  16286  6 20 22:47 INTEROP.md
-rw-r--r--@  1 jack  staff   1957  6 21 01:03 README.md
-rw-r--r--@  1 jack  staff   4606  6 20 22:47 RELEASE_NOTES.md
drwxr-xr-x@  8 jack  staff    272  6 20 23:04 bin
drwxr-xr-x   6 jack  staff    204  7 28 17:08 dependencies
drwxr-xr-x@  3 jack  staff    102  6 20 23:01 klib
drwxr-xr-x@  5 jack  staff    170  5 12 00:02 konan
drwxr-xr-x@  4 jack  staff    136  5 12 00:02 lib
drwxr-xr-x@ 22 jack  staff    748  6 22 19:04 samples

We will introduce the contents of this catalog in the following section.

In addition, we can also download the source code and compile it ourselves, so I won't talk about it here.

16.2.2 New Gradle Project

In this section, we first use IDEA to create a normal Gradle project.

Step 1, open File -> New -> Project, as shown below

Screenshot 2017-07-29 13.35.12.png

Step 2, create a new Gradle project. We directly select Gradle in the left column and click Next

Screenshot 2017-07-29 13.36.01.png

Step 3, set the GroupId, ArtifactId, Version information of the project

Screenshot 2017-07-29 13.36.47.png

The fourth step is to configure the basic settings of the Gradle project. We directly select the local Gradle environment directory to save download time (sometimes the network is not good, it takes a long time to download), the specific configuration is shown in the figure below

Screenshot 2017-07-29 13.37.11.png

Step 5, configure the project name and project storage directory, click Finish

Screenshot 2017-07-29 13.37.23.png

Step 6, waiting for IDEA to be created, we will get a Gradle project as follows

Screenshot 2017-07-29 13.38.50.png

There is nothing in this project now. Now let's start the original manual coding of new files.

16.2.3 Source Code Directory

First, we create a new src directory under the project root directory to store the source code. Create a new c directory under src to store C code, and a new kotlin directory to store Kotlin code. Our source code organization structure is designed as follows

src
├── c
│   ├── cn_kotlinor.c
│   ├── cn_kotlinor.h
└── kotlin
    └── main.kt

16.2.4 C code file

cn_kotlinor.h

The C header file is declared as follows

#ifndef CN_KOTLINOR_H
#define CN_KOTLINOR_H
void printHello();
int factorial(int n);
int fib(int n);
#endif

We simply declared 3 functions.

cn_kotlinor.c

The content of the C source code file is as follows

#include "cn_kotlinor.h"
#include <stdio.h>

void printHello(){
    printf("[C]HelloWorld\n");
}

int factorial(int n){
    printf("[C]calc factorial: %d\n", n);
    if(n == 0) return 1;
    return n * factorial(n - 1);
}

int fib(int n){
    printf("[C]calc fibonacci: %d\n", n);
    if(n==1||n==2) return 1;
    return fib(n-1) + fib(n-2);
}

This is the familiar C language code.

16.2.5 Kotlin code files

The content of the main.kt file is as follows

import ckotlinor.*

fun main(args: Array<String>) {
    printHello()
    (1..7).map(::factorial).forEach(::println)
    (1..7).map(::fib).forEach(::println)
}


Among them, it import kotlinor.*is the C interface package path after the C language code is compiled by clang. We will configure this path in konanInterop in the build.gradle configuration file below.

16.2.6 Konan plugin configuration

First, we add the build script buildscript closure in build.gradle

buildscript {
    repositories {
        mavenCentral()
        maven {
            url "https://dl.bintray.com/jetbrains/kotlin-native-dependencies"
        }
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-native-gradle-plugin:0.3"
    }
}

Here we have added the DSL plugin kotlin-native-gradle-plugin:0.3 for Gradle to build Kotlin Native projects. The version number here corresponds to the version number of the konan compiler we downloaded. We are using v0.3, so here we also use the 0.3 version of the plug-in. This plugin is published in the https://dl.bintray.com/jetbrains/kotlin-native-dependencies repository, so we added this repository in repositories.

Then, we apply the plugin konan

apply plugin: 'konan' 

Konan is a plugin used to compile Kotlin as native code.

16.2.7 konanInterop interoperable arrangement

konanInterop {
    ckotlinor {
        defFile 'kotlinor.def' // interop 的配置文件
        includeDirs "src/c" // C 头文件目录,可以传入多个
    }
}

konanInterop is mainly used to configure Kotlin's interface to call C. The configuration of konanInterop is handled by KonanInteropTask.kt in the konan plugin API (the source code of this class is at: https://github.com/JetBrains/kotlin-native/blob/master/tools/kotlin-native-gradle-plugin /src/main/kotlin/org/jetbrains/kotlin/gradle/plugin/KonanInteropTask.kt).

Here we declare ckotlino is the KonanInteropConfig object in the plug-in. We will quote this ckotlnor in the konanArtifacts below.

About konanInterop configuration options are

  konanInterop {
       pkgName {
           defFile <def-file>  
           pkg <package with stubs>
           target <target: linux/macbook/iphone/iphone_sim>
           compilerOpts <Options for native stubs compilation>
           linkerOpts <Options for native stubs >
           headers <headers to process> 
           includeDirs <directories where headers are located> 
           linkFiles <files which will be linked with native stubs>
           dumpParameters <Option to print parameters of task before execution>
       }
 
       // TODO: add configuration for konan compiler
 }

We briefly explain as shown in the table below

Configuration item Function Description
defFile Interoperability mapping configuration file
pkg The C header file is compiled and mapped to the package name of Kotlin
target Compile target platform: linux/macbook/iphone/iphone_sim, etc.
compilerOpts Compilation options
linkerOpts Link options
headers Header file to be processed
includeDirs Included header file directory
linkFiles Files linked with native stubs
dumpParameters Print Gradle task parameter option configuration

Among them, kotlinor.def is the configuration file for Kotlin Native and C language interoperability, we configure the mapping relationship between C source code and kotlin in kotlinor.def. The content of this file is as follows

kotlinor.def

headers=cn_kotlinor.h
compilerOpts=-Isrc/c

The same configuration, if we write in the konanInterop configuration in the build.gradle file as follows

konanInterop {
    ckotlinor {
        // defFile 'kotlinor.def' // interop 的配置文件
        compilerOpts '-Isrc/c'
        headers 'src/c/cn_kotlinor.h' // interop 的配置文件
        includeDirs "src/c" // C 头文件存放目录,可以传入多个
    }
}

For the analysis principle of this configuration file, please refer to the source code of the KonanPlugin.kt file (https://github.com/JetBrains/kotlin-native/blob/master/tools/kotlin-native-gradle-plugin/src/main/kotlin/ org/jetbrains/kotlin/gradle/plugin/KonanPlugin.kt).

16.2.8 konanArtifacts placement

In the konan plugin, we use konanArtifacts to configure compilation task execution.

konanArtifacts { 
    KotlinorApp { // (1)
        inputFiles fileTree("src/kotlin") // (2)
        useInterop 'ckotlinor' // (3)
        nativeLibrary fileTree('src/c/cn_kotlinor.bc') // (4)
        target 'macbook' // (5)
    }
}

Among them, the KotlinorApp name at (1) will generate KotlinorApp.kexe executable program named after this name after build.
(2) The inputFiles at (2) configures the Kotlin code directory, and the entry main for program execution is defined here.

(3) The useInterop configuration is which interoperability configuration is used. We are using the configuration ckotlnor in the previous konanInterop.

(4) The nativeLibrary is configured with local library files. We will talk about the compilation and generation of the'src/c/cn_kotlinor.bc' file below.

(5) The target configuration at the place is the target platform for compilation, here we configure it as'macbook'.

The optional configuration for konanArtifacts is as follows

 konanArtifacts {
 
       artifactName1 {
 
           inputFiles "files" "to" "be" "compiled"
 
           outputDir "path/to/output/dir"
 
           library "path/to/library"
           library File("Library")
 
           nativeLibrary "path/to/library"
           nativeLibrary File("Library")
 
           noStdLib
           produce "library"|"program"|"bitcode"
           enableOptimization
 
           linkerOpts "linker" "args"
           target "target"
 
           languageVersion "version"
           apiVersion "version"
 
     }
      artifactName2 {
 
           extends artifactName1

           inputDir "someDir"
           outputDir "someDir"
      }
 
   }

The konan compilation task configuration processing class is KonanCompileTask.kt (https://github.com/JetBrains/kotlin-native/blob/master/tools/kotlin-native-gradle-plugin/src/main/kotlin/org/jetbrains/kotlin /gradle/plugin/KonanCompileTask.kt).

16.2.9 Complete build.gradle configuration

The complete build.gradle configuration file content is as follows

group 'com.easy.kotlin'
version '1.0-SNAPSHOT'


buildscript {
    repositories {
        mavenCentral()
        maven {
            url "https://dl.bintray.com/jetbrains/kotlin-native-dependencies"
        }
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-native-gradle-plugin:0.3"
    }
}

apply plugin: 'konan' // konan 就是用来编译 Kotlin 为 native 代码的插件


konanInterop { // konanInterop 主要用来配置 Kotlin 调用 C 的接口
    ckotlinor {
        defFile 'kotlinor.def' // interop 的配置文件
        includeDirs "src/c" // C 头文件目录,可以传入多个
    }
}

konanArtifacts { //konanArtifacts 配置我们的项目
    KotlinorApp { // build 之后会生成 KotlinorApp.kexe 可执行程序
        inputFiles fileTree("src/kotlin") //kotlin 代码配置,项目入口 main 需要定义在这里
        useInterop 'ckotlinor' //使用前面的 konanInterop 里面的配置  kotlinor{ ... }
        nativeLibrary fileTree('src/c/cn_kotlinor.bc') //自己编译的 llvm 字节格式的依赖
        target 'macbook' // 编译的目标平台
    }
}

Reminder: Detailed configuration document about konan plugin: Gradle DSL https://github.com/JetBrains/kotlin-native/blob/master/GRADLE_PLUGIN.md

16.2.10 Use clang to compile C code

For practicality, we create a new shell script kclang.sh to simplify the command line input parameters for clang compilation

#!/usr/bin/env bash
clang -std=c99 -c $1 -o $2 -emit-llvm

In this way, we put kclang.sh in the C code directory, and then directly use the script to compile:

 kclang.sh cn_kotlinor.c cn_kotlinor.bc

We will get a cn_kotlinor.bc library file.

Tip: clang is a C/C++/Objective-C/Objective-C++ compiler written in C++, based on LLVM, and released under the LLVM BSD license. It is almost completely compatible with the GNU C language specification. For more information about clang, please refer to: http://clang.llvm.org/docs/index.html.

16.2.11 Configure Konan Compiler Home Directory

Finally, before performing the Gradle build, we also need to specify the konan compiler home directory. We create a new gradle.properties property configuration file under the project root directory, the content is as follows

konan.home=/Users/jack/soft/kotlin-native-macos-0.3

16.2.12 Performing a build operation

We directly click the Tasks ->build -> build command on the Gradle toolbar on the right side of IDEA to execute the build operation

Screenshot 2017-07-30 03.42.19.png

We will see the terminal output

15:12:02: Executing external task 'build'...
:assemble UP-TO-DATE
:check UP-TO-DATE
:downloadKonanCompiler
:genKotlinerInteropStubs
:compileKotlinerInteropStubs
KtFile: kotliner.kt
:compileKonanKotliner
KtFile: main.kt
ld: warning: object file (/var/folders/q5/kvt7_nsd6ngdw5qry4d99xv00000gn/T/combined697750051437954502.o) was built for newer OSX version (10.12) than being linked (10.11)
:compileKonan
:build

BUILD SUCCESSFUL in 29s
4 actionable tasks: 4 executed
15:12:31: External task execution finished 'build'.

After the build is completed, a KotlinorApp.kexe executable program will be generated under the build/konan/bin/ directory, which runs directly on Mac OS and no longer depends on the JVM environment. The complete build output directory tree we get is as follows

build
└── konan
    ├── bin
    │   ├── KotlinorApp.kexe
    │   └── KotlinorApp.kt.bc
    ├── interopCompiledStubs
    │   └── ckotlinorInteropStubs
    │       ├── ckotlinorInteropStubs
    │       │   ├── linkdata
    │       │   │   ├── module
    │       │   │   ├── package_ckotlinor
    │       │   │   └── root_package
    │       │   ├── manifest
    │       │   ├── resources
    │       │   └── targets
    │       │       └── macbook
    │       │           ├── kotlin
    │       │           │   └── program.kt.bc
    │       │           └── native
    │       └── ckotlinorInteropStubs.klib
    ├── interopStubs
    │   └── genCkotlinorInteropStubs
    │       └── ckotlinor
    │           └── ckotlinor.kt
    └── nativelibs
        └── genCkotlinorInteropStubs
            └── ckotlinorstubs.bc

16 directories, 10 files

Among them, in ckotlinor.kt, we can see that the konan compiler also generates the Kotlin interface corresponding to the C code for us

@file:Suppress("UNUSED_EXPRESSION", "UNUSED_VARIABLE")
package ckotlinor

import konan.SymbolName
import kotlinx.cinterop.*

fun printHello(): Unit {
    val res = kni_printHello()
    return res
}

@SymbolName("ckotlinor_kni_printHello")
private external fun kni_printHello(): Unit

fun factorial(n: Int): Int {
    val _n = n
    val res = kni_factorial(_n)
    return res
}

@SymbolName("ckotlinor_kni_factorial")
private external fun kni_factorial(n: Int): Int

fun fib(n: Int): Int {
    val _n = n
    val res = kni_fib(_n)
    return res
}

@SymbolName("ckotlinor_kni_fib")
private external fun kni_fib(n: Int): Int


In the Kotlin code, we call these functional interfaces mapped to C.

16.2.12 Execute kexe application

We execute KotlinorApp.kexe directly on the command line as follows

chatper16_kotlin_native_helloworld$ build/konan/bin/KotlinorApp.kexe  

We can see the following output:

[C]HelloWorld
[C]calc factorial: 1
[C]calc factorial: 0
[C]calc factorial: 2
...
[C]calc factorial: 2
[C]calc factorial: 1
[C]calc factorial: 0
1
2
6
24
120
720
5040
[C]calc fibonacci: 1
[C]calc fibonacci: 2
[C]calc fibonacci: 3
...
[C]calc fibonacci: 3
[C]calc fibonacci: 2
[C]calc fibonacci: 1
1
1
2
3
5
8
13

So far, we have completed a simple experience journey of Kotlin Native and C language interoperability in system-level programming.

We see that Kotlin Native still values ​​interoperability. It can efficiently call C functions, and even automatically generate the corresponding Kotlin interface from the C header file, carrying forward JetBrains's good tradition of serving developers!

However, during the experience, we also found that the entire process is relatively manual and cumbersome (for example, manually creating various configuration files, manually using clang to compile C code, etc.).

However, Kotlin Native's Gradle plugin is still quite good to use. I believe that IDEA will intelligently integrate Kotlin Native development in the future to facilitate system programming developers to complete project configuration and development coding work better and faster.

16.3 Introduction to Kotlin Native Compiler Konan

In this section, we briefly introduce the relevant content of the Kotlin Native compiler (mainly using Mac OS platform examples).

bin directory

Below the bin directory is the execution command line

cinterop       klib           konanc         kotlinc        kotlinc-native  run_konan

run_konan Is a real entry shell, its execution logic is

TOOL_NAME="$1"
shift

if [ -z "$JAVACMD" -a -n "$JAVA_HOME" -a -x "$JAVA_HOME/bin/java" ]; then
    JAVACMD="$JAVA_HOME/bin/java"
else
    JAVACMD=java
fi
[ -n "$JAVACMD" ] || JAVACMD=java
...
java_opts=(-ea \
            -Xmx3G \
            "-Djava.library.path=${NATIVE_LIB}" \
            "-Dkonan.home=${KONAN_HOME}" \
           -Dfile.encoding=UTF-8)

KONAN_JAR="${KONAN_HOME}/konan/lib/backend.native.jar"
KOTLIN_JAR="${KONAN_HOME}/konan/lib/kotlin-compiler.jar"
STUB_GENERATOR_JAR="${KONAN_HOME}/konan/lib/StubGenerator.jar"
INTEROP_INDEXER_JAR="${KONAN_HOME}/konan/lib/Indexer.jar"
INTEROP_JAR="${KONAN_HOME}/konan/lib/Runtime.jar"
HELPERS_JAR="${KONAN_HOME}/konan/lib/helpers.jar"
KLIB_JAR="${KONAN_HOME}/konan/lib/klib.jar"
UTILITIES_JAR="${KONAN_HOME}/konan/lib/utilities.jar"
KONAN_CLASSPATH="$KOTLIN_JAR:$INTEROP_JAR:$STUB_GENERATOR_JAR:$INTEROP_INDEXER_JAR:$KONAN_JAR:$HELPERS_JAR:$KLIB_JAR:$UTILITIES_JAR"
TOOL_CLASS=org.jetbrains.kotlin.cli.utilities.MainKt

LIBCLANG_DISABLE_CRASH_RECOVERY=1 \
$TIMECMD "$JAVACMD" "${java_opts[@]}" "${java_args[@]}" -cp "$KONAN_CLASSPATH" "$TOOL_CLASS" "$TOOL_NAME" "${konan_args[@]}"

We can see that the operating environment of Kotlin Native compiler konan is still on the JVM, but the executable program of the machine code it generates runs directly on the corresponding platform system (directly compiled into machine language).

konan catalog

The konan directory is the core implementation part of the Kotlin Native compiler. The directory structure is as follows:

kotlin-native-macos-0.3$ tree konan
konan/
├── konan.properties
├── lib
│   ├── Indexer.jar
│   ├── Runtime.jar
│   ├── StubGenerator.jar
│   ├── backend.native.jar
│   ├── callbacks
│   │   └── shared
│   │       └── libcallbacks.dylib
│   ├── clangstubs
│   │   └── shared
│   │       └── libclangstubs.dylib
│   ├── helpers.jar
│   ├── klib.jar
│   ├── kotlin-compiler.jar
│   ├── protobuf-java-2.6.1.jar
│   └── utilities.jar
└── nativelib
    ├── libcallbacks.dylib
    ├── libclangstubs.dylib
    ├── libllvmstubs.dylib
    └── liborgjetbrainskotlinbackendkonanhashstubs.dylib

6 directories, 16 files

We can see the run_konandependence of these top jar package command line shell. The above catalog file is on the Mac OS platform.

The corresponding konan directory file on the Linux platform is as follows

kotlin-native-linux-0.3$ tree konan
konan
├── konan.properties
├── lib
│   ├── Indexer.jar
│   ├── Runtime.jar
│   ├── StubGenerator.jar
│   ├── backend.native.jar
│   ├── callbacks
│   │   └── shared
│   │       └── libcallbacks.so
│   ├── clangstubs
│   │   └── shared
│   │       └── libclangstubs.so
│   ├── helpers.jar
│   ├── klib.jar
│   ├── kotlin-compiler.jar
│   ├── protobuf-java-2.6.1.jar
│   └── utilities.jar
└── nativelib
    ├── libcallbacks.so
    ├── libclangstubs.so
    ├── libllvmstubs.so
    └── liborgjetbrainskotlinbackendkonanhashstubs.so

6 directories, 16 files

The konan directory file on the Windows platform is as follows

kotlin-native-windows-0.3$ tree konan
konan
├── konan.properties
├── lib
│   ├── Indexer.jar
│   ├── Runtime.jar
│   ├── StubGenerator.jar
│   ├── backend.native.jar
│   ├── callbacks
│   │   └── shared
│   │       └── callbacks.dll
│   ├── clangstubs
│   │   └── shared
│   │       └── clangstubs.dll
│   ├── helpers.jar
│   ├── klib.jar
│   ├── kotlin-compiler.jar
│   ├── protobuf-java-2.6.1.jar
│   └── utilities.jar
└── nativelib
    ├── callbacks.dll
    ├── clangstubs.dll
    ├── llvmstubs.dll
    └── orgjetbrainskotlinbackendkonanhashstubs.dll

6 directories, 16 files

klib directory

Under the klib directory are the associated metadata files of Kotlin's standard library and Kotlin Native's bc files for each target platform

kotlin-native-macos-0.3$ tree klib
klib/
└── stdlib
    ├── linkdata
    │   ├── module
    │   ├── package_konan
    │   ├── package_konan.internal
    │   ├── package_kotlin
    │   ├── package_kotlin.annotation
    │   ├── package_kotlin.collections
    │   ├── package_kotlin.comparisons
    │   ├── package_kotlin.coroutines
    │   ├── package_kotlin.coroutines.experimental
    │   ├── package_kotlin.coroutines.experimental.intrinsics
    │   ├── package_kotlin.experimental
    │   ├── package_kotlin.internal
    │   ├── package_kotlin.io
    │   ├── package_kotlin.properties
    │   ├── package_kotlin.ranges
    │   ├── package_kotlin.reflect
    │   ├── package_kotlin.sequences
    │   ├── package_kotlin.text
    │   ├── package_kotlin.text.regex
    │   ├── package_kotlin.util
    │   ├── package_kotlinx
    │   ├── package_kotlinx.cinterop
    │   └── root_package
    ├── manifest
    ├── resources
    └── targets
        ├── android_arm32
        │   ├── kotlin
        │   │   └── program.kt.bc
        │   └── native
        │       ├── launcher.bc
        │       ├── runtime.bc
        │       └── start.bc
        ├── android_arm64
        │   ├── kotlin
        │   │   └── program.kt.bc
        │   └── native
        │       ├── launcher.bc
        │       ├── runtime.bc
        │       └── start.bc
        ├── iphone
        │   ├── kotlin
        │   │   └── program.kt.bc
        │   └── native
        │       ├── launcher.bc
        │       ├── runtime.bc
        │       ├── start.bc
        │       ├── start.kt.bc
        │       └── stdlib.kt.bc
        └── macbook
            ├── kotlin
            │   └── program.kt.bc
            └── native
                ├── launcher.bc
                ├── runtime.bc
                └── start.bc

16 directories, 42 files

The above directory is the version of the kotlin-native-macos-0.3 platform. We can see that on Mac OS, we can use Kotlin Native to compile machine code executable programs for target platforms such as android_arm32, android_arm64, iphone, macbook, etc.

In addition, the corresponding directory files of the Linux platform are as follows

kotlin-native-linux-0.3$ tree klib
klib/
└── stdlib
    ├── linkdata
    │   ├── module
    │   ├── package_konan
    │   ├── package_konan.internal
    │   ├── package_kotlin
    │   ├── package_kotlin.annotation
    │   ├── package_kotlin.collections
    │   ├── package_kotlin.comparisons
    │   ├── package_kotlin.coroutines
    │   ├── package_kotlin.coroutines.experimental
    │   ├── package_kotlin.coroutines.experimental.intrinsics
    │   ├── package_kotlin.experimental
    │   ├── package_kotlin.internal
    │   ├── package_kotlin.io
    │   ├── package_kotlin.properties
    │   ├── package_kotlin.ranges
    │   ├── package_kotlin.reflect
    │   ├── package_kotlin.sequences
    │   ├── package_kotlin.text
    │   ├── package_kotlin.text.regex
    │   ├── package_kotlin.util
    │   ├── package_kotlinx
    │   ├── package_kotlinx.cinterop
    │   └── root_package
    ├── manifest
    ├── resources
    └── targets
        ├── android_arm32
        │   ├── kotlin
        │   │   └── program.kt.bc
        │   └── native
        │       ├── launcher.bc
        │       ├── runtime.bc
        │       └── start.bc
        ├── android_arm64
        │   ├── kotlin
        │   │   └── program.kt.bc
        │   └── native
        │       ├── launcher.bc
        │       ├── runtime.bc
        │       └── start.bc
        ├── linux
        │   ├── kotlin
        │   │   └── program.kt.bc
        │   └── native
        │       ├── launcher.bc
        │       ├── runtime.bc
        │       └── start.bc
        └── raspberrypi
            ├── kotlin
            │   └── program.kt.bc
            └── native
                ├── launcher.bc
                ├── runtime.bc
                ├── start.bc
                ├── start.kt.bc
                └── stdlib.kt.bc

16 directories, 42 files

In other words, we can compile target programs on platforms such as android_arm32, android_arm64, linux, raspberrypi, etc. on the Linux platform.

The corresponding Windows platform is as follows

kotlin-native-windows-0.3$ tree klib
klib/
└── stdlib
    ├── linkdata
    │   ├── module
    │   ├── package_konan
    │   ├── package_konan.internal
    │   ├── package_kotlin
    │   ├── package_kotlin.annotation
    │   ├── package_kotlin.collections
    │   ├── package_kotlin.comparisons
    │   ├── package_kotlin.coroutines
    │   ├── package_kotlin.coroutines.experimental
    │   ├── package_kotlin.coroutines.experimental.intrinsics
    │   ├── package_kotlin.experimental
    │   ├── package_kotlin.internal
    │   ├── package_kotlin.io
    │   ├── package_kotlin.properties
    │   ├── package_kotlin.ranges
    │   ├── package_kotlin.reflect
    │   ├── package_kotlin.sequences
    │   ├── package_kotlin.text
    │   ├── package_kotlin.text.regex
    │   ├── package_kotlin.util
    │   ├── package_kotlinx
    │   ├── package_kotlinx.cinterop
    │   └── root_package
    ├── manifest
    ├── mingw
    │   ├── kotlin
    │   │   └── program.kt.bc
    │   └── native
    │       ├── launcher.bc
    │       ├── runtime.bc
    │       └── start.bc
    ├── resources
    └── targets
        └── mingw
            ├── kotlin
            │   └── program.kt.bc
            └── native
                ├── launcher.bc
                ├── runtime.bc
                └── start.bc

10 directories, 32 files

On the Windows platform, Kotlin Native is implemented using the mingw library. Currently, in the pre-release version of V0.3, there are few things we can experience on the Windows platform, such as Android, iOS, and Raspberrypi are not yet supported.

Tip: MinGW is the abbreviation of Minimalist GNUfor Windows. It is a collection of freely available and freely distributed Windows-specific header files and import libraries using the GNU tool set, allowing you to generate native Windows programs on GNU/Linux and Windows platforms without the need for a third-party C Runtime (C Runtime) Library. MinGW is a set of include files and port libraries. Its function is to allow console mode programs to use Microsoft's standard C Runtime library (MSVCRT.DLL). This library is valid on all NT OSs. The Windows OS above the Windows 95 release version is valid. When using the basic runtime, you can use GCC to write console mode conforming to the American Standards Organization (ANSI) program, and you can use the C Runtime extension provided by Microsoft to compare with the basic runtime. Combining time, you can have full rights to use both CRT (C Runtime) and Windows API functions.

samples directory

Below the samples directory are some official examples. The document introduction and source code project for these examples are: https://github.com/JetBrains/kotlin-native/tree/master/samples. Students who want to know more about learning can refer to it.

chapter summary

The source code of this chapter: https://github.com/EasyKotlin/chatper16_kotlin_native_helloworld

Now we can run the machine code that Kotlin directly compiles like C, so where C language appears (for example, when it is used in embedded scenarios with high performance requirements), Kotlin also comes. Kotlin will continue to make efforts in the fields of embedded systems and Internet of Things, data analysis and scientific computing, game development, server-side development and microservices.

The architecture of Kotlin’s entire language is not unambiguous: it is on the cloud (server program), it is on the mobile phone (Kotlin / Native), it is written on the front end (JS, HTML DSL, etc.), and the refrigerator is embedded (Kotlin Native). ). Kotlin has become a language that excels in many fields.

In the field of the Internet, Kotlin is currently the most active area in the development of Web server applications and Android mobile development. Kotlin will increasingly enter the vision of Java programmers, and Java programmers will gradually fall in love with Kotlin.

There are many possibilities in the future. But the real future still requires us to create.


Kotlin Developer Community

Focus on sharing Java, Kotlin, Spring/Spring Boot, MySQL, redis, neo4j, NoSQL, Android, JavaScript, React, Node, functional programming, programming ideas, "high availability, high performance, high real-time" large-scale distributed system architecture design theme.

High availability, high performance, high real-time large-scale distributed system architecture design

Distributed framework: Zookeeper, distributed middleware framework, etc.
Distributed storage: GridFS, FastDFS, TFS, MemCache, redis, etc.
Distributed database: Cobar, tddl, Amoeba, Mycat
cloud computing, big data, AI algorithm
virtualization, cloud native Technology
Distributed computing framework: MapReduce, Hadoop, Storm, Flink, etc.
Distributed communication mechanism: Dubbo, RPC calls, shared remote data, message queues, etc.
Message queue MQ: Kafka, MetaQ, RocketMQ
how to build a highly available system: based on hardware, software Realization of some typical solutions such as middleware and system architecture: HAProxy, Corosync+Pacemaker-based high-availability cluster suite middleware system
Mycat architecture distributed evolution
The problems behind big data Join: contradictions and reconciliation of data, network, memory and computing capabilities
High-performance problems in Java distributed systems: AIO, NIO, Netty or self-developed frameworks?
High-performance event dispatch mechanism: thread pool model, Disruptor model, etc. . .

The embracing wood is born at the end of the mill; the nine-story platform starts from the basement; the journey of a thousand miles begins with a single step. If you don't accumulate steps, you can't reach a thousand miles; if you don't accumulate small streams, you can't become a river.

Introduction to Kotlin

Kotlin is a non-research language. It is a very pragmatic industrial-grade programming language. Its mission is to help programmers solve problems in actual engineering practice. Using Kotlin makes the lives of Java programmers better. The null pointer errors in Java, the lengthy boilerplate code that wastes time, the verbose syntax restrictions, etc., all disappear in Kotlin. Kotlin is simple and pragmatic, with concise and powerful syntax, safe and expressive, and extremely productive.

Java was born in 1995 and has a history of 23 years. The current latest version is Java 9. In the process of continuous development and prosperity of the JVM ecosystem, brother languages ​​such as Scala, Groovy, and Clojure were also born.

Kotlin is also an excellent member of the JVM family. Kotlin is a modern language (version 1.0 was released in February 2016). Its original purpose is to optimize the defects of the Java language like Scala, provide simpler and more practical programming language features, and solve performance problems, such as compilation time. JetBrains has done a great job in these areas.

Features of Kotlin language

After developing in Java for many years, it's great to be able to try something new. If you are a Java developer, Kotlin will be very natural and smooth. If you are a Swift developer, you will feel familiar, such as Nullability. The features of Kotlin language are:

1. Concise

Significantly reduce the amount of boilerplate code.

2. 100% interoperability with Java

Kotlin can directly interact with Java classes and vice versa. This feature allows us to directly reuse our code base and migrate it to Kotlin. Because Java's interoperability is almost everywhere. We can directly access platform APIs and existing code bases, while still enjoying and using all the powerful modern language features of Kotlin.

3. Extension function

Kotlin is similar to C# and Gosu, it provides the ability to provide new functional extensions for existing classes without having to inherit from the class or use any type of design patterns (such as decorator patterns).

4. Functional programming

The Kotlin language first supports functional programming, just like Scala. It has basic functional features such as high-order functions and lambda expressions.

5. Default and named parameters

In Kotlin, you can set a default value for the parameters in a function and give each parameter a name. This helps to write easy-to-read code.

6. Powerful development tool support

And because it is produced by JetBrains, we have great IDE support. Although the automatic conversion from Java to Kotlin is not 100% OK, it is indeed a very good tool. When using IDEA's tools to convert Java code to Kotlin code, 60%-70% of the resulting code can be reused easily, and the cost of modification is small.

In addition to its concise and powerful syntax features, Kotlin also has a very practical API and an ecosystem built around it. For example: collection API, IO extension, reflection API, etc. At the same time, the Kotlin community also provides a wealth of documents and a lot of learning materials, as well as online REPL.

A modern programming language that makes developers happier. Open source forever

Picture from "Kotlin from entry to advanced combat" (Chen Guangjian, Tsinghua University Press)

Picture from "Kotlin from entry to advanced combat" (Chen Guangjian, Tsinghua University Press)

https://kotlinlang.org/

Guess you like

Origin blog.csdn.net/universsky2015/article/details/108669500