Get Started
Kotlin Native 支持直接将 Kotlin 代码编译到目标平台,彻底摆脱 JVM 虚拟机。在 IDEA 中新建 Kotlin Native 项目并构建时,IDEA 会下载大约 2GB 的编译工具到 C:\Users\Admin.konan 文件夹中,其中包括 300MB 的 kotlin-native-windows-1.3.1 和 1.87GB 的依赖项,主要是 LLVM-Clang 编译器和 MSYS2-MinGW 平台环境。编译过程需要约 40 秒,速度较慢。
图形化 Hello World
默认模板仅生成打印字符串的命令行程序,大小约为 1MB。Kotlin Native 同样支持构建图形化应用程序。若要创建窗口程序,需修改 build.gradle 文件,在 kotlin.targets.mingwX64.binaries.executable 块内插入以下链接器设置:
linkerOpts("-Wl,--subsystem,windows")
这相当于在 Visual Studio 中修改子系统设置。
以下是一个简单的 Win32 GUI 示例代码:
package sample
import kotlinx.cinterop.*
import platform.windows.*
@ExperimentalUnsignedTypes
fun WndProc(hwnd: HWND?, msg: UINT, wParam: WPARAM, lParam: LPARAM) : LRESULT
{
when(msg)
{
WM_CLOSE.toUInt() -> DestroyWindow(hwnd)
WM_DESTROY.toUInt() -> PostQuitMessage(0)
WM_COMMAND.toUInt() -> {
// 控制特定操作示例
}
}
return (DefWindowProc!!)(hwnd, msg, wParam, lParam)
}
val UI_WNDSTYLE_FRAME = (WS_VISIBLE or WS_OVERLAPPEDWINDOW).toUInt()
val UI_CLASSSTYLE_FRAME = (CS_VREDRAW or CS_HREDRAW).toUInt()
@ExperimentalUnsignedTypes
fun main() {
println("Hello, Kotlin/Native!")
memScoped {
val hInstance = (GetModuleHandle!!)(null)
val lpszClassName = "SAMPLE"
val wc = alloc<WNDCLASSEX>()
wc.cbSize = sizeOf<WNDCLASSEX>().toUInt()
wc.style = UI_CLASSSTYLE_FRAME
wc.lpfnWndProc = staticCFunction(::WndProc)
wc.cbClsExtra = 0
wc.cbWndExtra = 0
wc.hInstance = hInstance
wc.hIcon = null
wc.hCursor = (LoadCursor!!)(hInstance, IDC_ARROW)
wc.hbrBackground = null
wc.lpszMenuName = null
wc.lpszClassName = lpszClassName.wcstr.ptr
wc.hIconSm = null
if((RegisterClassEx!!)(wc.ptr) == 0u.toUShort()) {
println("Failed to register!")
return
}
val hwnd = CreateWindowExA(
(WS_EX_STATICEDGE or WS_EX_APPWINDOW).toUInt(),
lpszClassName,
"KN - Win32 HELLOWORLD",
UI_WNDSTYLE_FRAME,
CW_USEDEFAULT,
CW_USEDEFAULT,
320,
125,
null,
null,
hInstance,
NULL
)
ShowWindow(hwnd, 1)
UpdateWindow(hwnd)
val Msg = alloc<MSG>()
while((GetMessage!!)(Msg.ptr, null, 0u, 0u) > 0) {
TranslateMessage(Msg.ptr)
(DispatchMessage!!)(Msg.ptr)
}
}
}
编译速度仍然较慢,且相关系统调用缺乏自动完成和参数提示。尽管使用 Kotlin 编写原生窗口程序很酷,但该技术目前仍处于实验阶段。
参考
- Kotlin Native 指南:http://www.kotlincn.net/docs/reference/native-overview.html
- 使用 IntelliJ IDEA 入门:http://www.kotlincn.net/docs/tutorials/native/using-intellij-idea.html
- Kotlin Native Win32 GUI 示例:https://gist.github.com/Eng-Fouad/c810fae1ddcb0f0c4538299e31c78638