kotlin native 入门&进阶

kotlin-native02 编写动态链接库

2019-05-29  本文已影响0人  hohov

开发工具

创建工程

kotlin {
    // For ARM, should be changed to iosArm32 or iosArm64
    // For Linux, should be changed to e.g. linuxX64
    // For MacOS, should be changed to e.g. macosX64
    // For Windows, should be changed to e.g. mingwX64
    mingwX64("mingw") {
        binaries {
            /*executable {
                // Change to specify fully qualified name of your application's entry point:
               entryPoint = 'sample.main'
                // Specify command-line arguments, if necessary:
                runTask?.args('')
            }*/
            sharedLib {
                baseName = "kotlinlib"
            }
        }
    }
    sourceSets {
        // Note: To enable common source sets please comment out 'kotlin.import.noCommonSourceSets' property
        // in gradle.properties file and re-import your project in IDE.
        mingwMain {
        }
        mingwTest {
        }
    }
}
编译动态库
package sample

object Object {
    val field = "A"
}

class Clazz {
    fun memberFunction(p: Int): ULong = 42UL
}

fun forIntegers(b: Byte, s: Short, i: UInt, l: Long) {
    println("Byte is: $b")
    println("Short is: $s")
    println("UInt is: $i")
    println("Long is: $l")
}
fun forFloats(f: Float, d: Double) {
    println("Float is $f")
    println("Double is $d")
}

fun strings(str: String): String? {
    return "That is '$str' from C"
}

val globalString = "A global String"

使用生成的动态库

cmake_minimum_required(VERSION 3.14)
project(invokekotlindll)

set(CMAKE_CXX_STANDARD 11)

#指定lib目录
link_directories(lib)

add_executable(invokekotlindll main.cpp)

target_link_libraries(invokekotlindll kotlinlib.dll)
#include <iostream>
#include "kotlinlib_api.h"

int main() {

    kotlinlib_ExportedSymbols *lib = kotlinlib_symbols();

    lib->kotlin.root.sample.forIntegers(1, 2, 3, 4);
    lib->kotlin.root.sample.forFloats(1.0f, 2.0);

    const char *str = "Hello from Native!";
    const char *response = lib->kotlin.root.sample.strings(str);
    printf("in: %s\nout:%s\n", str, response);
    lib->DisposeString(response);

    kotlinlib_kref_sample_Clazz newInstance = lib->kotlin.root.sample.Clazz.Clazz();
    long x = lib->kotlin.root.sample.Clazz.memberFunction(newInstance, 42);
    lib->DisposeStablePointer(newInstance.pinned);

    printf("DemoClazz returned %ld\n", x);

    return 0;
}
上一篇 下一篇

猜你喜欢

热点阅读