kotlin-native02 编写动态链接库

开发工具

  • IntelliJ IDEA 2019或 Clion 2019

创建工程

  • 新建工程的部分请参考上一篇文章,这里偷个懒,依旧使用上一篇的工程
  • 新建完成后修改build.gradle的配置,将kotlin->mingwX64->binaries中executable部分注释掉,改为
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 {
        }
    }
}
编译动态库
  • 接下来修改SampleMingw.kt
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"
  • 然后双击Ctrl,输入gradle linkReleaseSharedMingw,回车
    Run Anything
  • 这是build目录的文件,可以看到生成了头文件、动态链接库和一个def文件
    build
  • 这是导出的头文件
    kotlinlib_api.h

使用生成的动态库

  • 使用Clion新建一个C++项目
    新建项目
  • 将上面生成的头文件和dll文件拷贝到工程中,目录结构如图
    工程结构
  • 修改CMakeLists.txt,增加两行代码link_directories(lib)target_link_libraries(invokekotlindll kotlinlib.dll)
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)
  • 修改main.cpp
#include 
#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;
}
  • 修改项目运行配置
    修改配置

    将lib目录添加到PATH
  • 然后就可以运行项目了
    运行结果

你可能感兴趣的:(kotlin-native02 编写动态链接库)