Skip to content
This repository has been archived by the owner on Apr 13, 2023. It is now read-only.

Latest commit

 

History

History
72 lines (53 loc) · 6.26 KB

Kotlin Native v0.5 released calling Kotlin from Swift and C LLVM 5 and more.md

File metadata and controls

72 lines (53 loc) · 6.26 KB
Error in user YAML: (<unknown>): mapping values are not allowed in this context at line 1 column 35
---
title: Kotlin/Native v0.5 released: calling Kotlin from Swift and C, LLVM 5 and more
author: Nikolay Igotti
date: 2017-12-19 17:16:00
tags: 
categories: 官方动态
reward: false
reward_title: Have a nice Kotlin!
reward_wechat:
reward_alipay:
source_url: https://blog.jetbrains.com/kotlin/2017/12/kotlinnative-v0-5-released-calling-kotlin-from-swift-and-c-llvm-5-and-more/
translator: pye52 & 黄志强
translator_url: https://pye52.github.io/ & https://suima0v0.github.io/
---

我们很高兴地宣布Kotlin / Native 迎来了0.5圣诞版!该版本支持将Kotlin / Native嵌入到C,Objective-C和Swift代码中,同时可以使用iOS模拟器开发了,LLVM 5也被纳入到支持中,以及可以在Linux和Windows的主机中创建WebAssembly。

Objective-C和Swift的reverse interop

我们曾经在之前的版本中提及过,如何在Kotlin / Native中调用Apple框架,但前提是存在Objective-C头文件。现在我们换了一种方式,以支持从Swift和Objective-C调用Kotlin的代码。为此我们提供了一个新的编译器选项-produce framework。它将生成一个独立的框架,可以从应用程序的其他地方调用,就好像它本身就是用Swift编写的一样。下面让我们来看看这个计算器例子。它的界面采用的是Swift编写,而计算逻辑则采用Kotlin编写。Swift代码与Kotlin完美混合。例如,这行Swift代码:

private let parser = KAPPartialParser(composer: KAPCalculator(), partialComposer: PartialRenderer())

创建Kotlin类PartialParser的实例,并将实现了Kotlin接口ExpressionComposer的Swift类PartialRenderer实例赋予给它。 请注意,像numbers和strings这样的基本类型在Swift和Kotlin中的映射是透明的。 若要构建项目,只需在XCode中打开,然后设置为真实设备或模拟器进行编译,请参阅README.md了解更加详细的信息。

Screen Shot 2017-12-18 at 18.40.21

IntelliJ IDEA中的Kotlin代码:

Screen Shot 2017-12-18 at 19.44.38

Reverse interop from C

我们也对其他平台提供reverse interop的特性,允许从外部调用Kotlin / Native代码。现代底层语言的标准是C,所以这是我们需要进行互操作的语言。开启编译器选项-produce dynamic将会生成一个动态库(如同macOS上的.dylib,Linux上的.so和Windows上的.dll),其中包含调用Kotlin / Native代码所需的所有内容。为了更容易理解,我们决定通过Python扩展来演示这种互操作性。Python调用C的实现,而C调用Kotlin的实现,参考以下例子

if (PyArg_ParseTuple(args, "Lss", &session_arg, &string_arg1, &string_arg2)) {
       T_(Server) server = getServer();
       T_(Session) session = { (void*)(uintptr_t)session_arg };
       const char* string = __ kotlin.demo.Server.concat(server, session, string_arg1, string_arg2);
       result = Py_BuildValue("s", string);
       __ DisposeString(string);
    } else {
        result = Py_BuildValue("s", NULL);
    }

Kotlin / Native编译器将生成一个动态库,而Python distutils构建工具生成另一个起决定作用的动态库。Python起始代码通过C来桥接Kotlin / Native转换的对象和原始类型。

其他改进

  • 在Kotlin 1.2中,kotlin.math包被添加到Kotlin标准库中。Kotlin / Native v0.5版也支持kotlin.math包中的函数
  • 得益于对clang工具链、bitcode codegenerator和优化器的支持,LLVM 5.0.0也在这个版本中得到支持。
  • 现在可以在Linux和Windows系统的主机上生成WebAssembly目标代码(-target wasm32)(在这之前只支持macOS系统)
  • Workers API得到了这些改进:允许更方便地使用worker的执行结果和允许与worker交互初始值
  • 其他bug的改进及性能提升

获取二进制包

可以在以下链接下载二进制包:

反馈

若遇到问题请向Kotlin bug 跟踪器提交报告。欢迎在Slackkotlin本地频道上讨论。(获得邀请