kotlin native 調用C靜態庫

準備環境

  1. 安裝fedora31
  2. 編譯kotlin native
  3. 創建 hello.h 頭文件,在其中輸入如下代碼
#ifndef HELLO_H 
#define HELLO_H 

void sayHello();

#endif
  1. 創建hello.c文件,在其中輸入如下代碼
#include "hello.h"
#include <stdio.h>

void sayHello()
{
    printf("Hello Kotlin Native\n");
}
  1. 編譯hello.c,生成靜態鏈接庫
mkdir lib

gcc -c hello.c
ar rcs lib/libmyhello.a hello.o
  1. 創建hello.def文件

    headers=hello.h
    headerFilter=hello.h
    package=hello
    staticLibraries = libmyhello.a #靜態庫的名稱
    libraryPaths= /tmp/kotlin/lib #靜態庫的搜索路徑

    libmyhello.a會包含進同cinterop生成的hello.klib文件中

  2. 執行如下命令用以分析hello.h文件,並自動生成kotlin定義
cinterop -def hello.def -compiler-option -I. -o hello
  1. 命令執行後的結果
    kotlin native 調用C靜態庫
  2. 創建main.kt文件
import hello.*

fun main(args: Array<String>)
{
sayHello()
}
  1. 編譯main.kt
    kotlinc main.kt -library hello  -o main
  2. 執行文件
    kotlin native 調用C靜態庫

  3. 參考鏈接
    https://github.com/plter/SimpleKotlinNativeCallCDemo
    https://github.com/JetBrains/kotlin-native/blob/master/INTEROP.md
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章