You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否将C++代码封装为Kotlin/Native .klib?iOS集成及调用求助

核心结论

可以将带有C头文件的C++库封装为Kotlin/Native .klib,并且能在iOS平台直接调用,以下是具体实现步骤和iOS调用方案:


一、封装C++库为.klib的步骤

1. 先将C++接口转为C兼容格式

Kotlin/Native对C的交互支持更直接,C++需要通过extern "C"导出无名称修饰的接口,避免编译后符号无法识别:

// wrapper.h(对外暴露的C兼容头文件)
#ifdef __cplusplus
extern "C" {
#endif

// 导出简单函数
int add(int a, int b);

// 封装C++类(Kotlin无法直接调用C++类,需通过句柄操作)
typedef void* MyClassHandle;
MyClassHandle createMyClass(int initialValue);
void myClassUpdateValue(MyClassHandle handle, int newValue);
int myClassGetValue(MyClassHandle handle);
void destroyMyClass(MyClassHandle handle);

#ifdef __cplusplus
}
#endif

对应的C++实现:

// wrapper.cpp
#include "wrapper.h"
#include "your_original_cpp_library.h" // 引入你的原生C++库头文件

int add(int a, int b) {
    return a + b;
}

MyClassHandle createMyClass(int initialValue) {
    return new YourCppClass(initialValue);
}

void myClassUpdateValue(MyClassHandle handle, int newValue) {
    static_cast<YourCppClass*>(handle)->setValue(newValue);
}

int myClassGetValue(MyClassHandle handle) {
    return static_cast<YourCppClass*>(handle)->getValue();
}

void destroyMyClass(MyClassHandle handle) {
    delete static_cast<YourCppClass*>(handle);
}

2. 创建Kotlin Native Gradle项目

在build.gradle.kts中配置多平台编译和C/C++交互:

plugins {
    kotlin("multiplatform") version "1.9.20"
}

kotlin {
    // 声明iOS目标架构
    iosX64()
    iosArm64()
    iosSimulatorArm64()

    sourceSets {
        val nativeMain by getting {}
    }

    // 配置Cinterop绑定
    targets.withType<org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget> {
        compilations.getByName("main") {
            cinterops.create("MyCppLib") {
                // 指定C头文件目录
                includeDirs("src/nativeMain/cpp/include")
                // C++编译参数
                compilerOpts("-std=c++17")
                // 如果依赖第三方静态库,添加链接参数
                // linkerOpts("-L/path/to/static/libs", "-lyour_cpp_static_lib")
            }
        }
    }
}

项目目录结构:

project-root/
├── src/
│   └── nativeMain/
│       ├── cpp/
│       │   ├── include/
│       │   │   └── wrapper.h
│       │   └── wrapper.cpp
│       └── kotlin/
│           └── (可选:编写Kotlin封装层,简化iOS端调用)
└── build.gradle.kts

3. 生成.klib

执行Gradle命令:

./gradlew assemble

生成的.klib文件会位于build/libs/目录下,对应不同iOS架构版本。


二、iOS项目中调用.klib

1. 集成方式(推荐CocoaPods)

在iOS项目的Podfile中添加本地依赖:

pod 'MyKotlinCppLib', :path => '../path/to/your/klib/project'

执行pod install完成集成。

2. Swift端调用示例

先在Kotlin层做封装(简化Swift调用):

// src/nativeMain/kotlin/CppWrapper.kt
package com.example

import kotlinx.cinterop.*
import com.example.MyCppLib.*

// 封装简单函数
fun addNumbers(a: Int, b: Int): Int = add(a, b)

// 封装C++类
class MyCppClass(private val handle: MyClassHandle) {
    constructor(initialValue: Int) : this(createMyClass(initialValue))

    var value: Int
        get() = myClassGetValue(handle)
        set(newValue) = myClassUpdateValue(handle, newValue)

    fun destroy() {
        destroyMyClass(handle)
    }
}

Swift代码中调用:

import MyKotlinCppLib

// 调用简单函数
let sum = CppWrapper.addNumbers(a: 3, b: 5)
print(sum) // 输出8

// 调用封装的C++类
let cppClass = CppWrapper.MyCppClass(initialValue: 10)
print(cppClass.value) // 输出10
cppClass.value = 20
print(cppClass.value) // 输出20
cppClass.destroy()

3. 直接通过Xcode导入(不推荐)

将.klib拖入Xcode项目,在Build Settings的Other Kotlin Flags中添加:

-cp /path/to/your.klib

之后即可在Swift/Objective-C中直接调用Cinterop生成的API。


三、模板参考

可直接通过IntelliJ IDEA或Android Studio新建Kotlin Multiplatform项目,选择iOS目标,再按照上述步骤添加C/C++交互代码即可,官方模板已包含基础的Gradle配置结构。

内容的提问来源于stack exchange,提问作者Jørgen Svennevik Notland

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 01:05:18