準備環境
- 安裝fedora31
- 編譯kotlin native
- 創建 hello.h 頭文件,在其中輸入如下代碼
#ifndef HELLO_H
#define HELLO_H
void sayHello();
#endif
- 創建hello.c文件,在其中輸入如下代碼
#include "hello.h"
#include <stdio.h>
void sayHello()
{
printf("Hello Kotlin Native\n");
}
- 編譯hello.c,生成靜態鏈接庫
mkdir lib
gcc -c hello.c
ar rcs lib/libmyhello.a hello.o
-
創建hello.def文件
headers=hello.h headerFilter=hello.h package=hello staticLibraries = libmyhello.a #靜態庫的名稱 libraryPaths= /tmp/kotlin/lib #靜態庫的搜索路徑
libmyhello.a會包含進同cinterop生成的hello.klib文件中
- 執行如下命令用以分析hello.h文件,並自動生成kotlin定義
cinterop -def hello.def -compiler-option -I. -o hello
- 命令執行後的結果
- 創建main.kt文件
import hello.*
fun main(args: Array<String>)
{
sayHello()
}
- 編譯main.kt
kotlinc main.kt -library hello -o main
-
執行文件
- 參考鏈接
https://github.com/plter/SimpleKotlinNativeCallCDemo
https://github.com/JetBrains/kotlin-native/blob/master/INTEROP.md