如何在KMM的iosMain模块中引用C++代码?
在KMM的iosMain中调用C++代码的可行方案
方法一:通过Objective-C++中间层对接
Kotlin/Native原生支持与Objective-C互操作,你可以借助Objective-C封装C逻辑,再让iosMain的Kotlin代码调用Objective-C接口,步骤如下:
- 封装C++为Objective-C接口
先写纯Objective-C风格的头文件(避免Kotlin interop处理C语法),再用Objective-C实现文件调用C++代码:// CPPWrapper.h(纯Objective-C头文件) #import <Foundation/Foundation.h> @interface CPPWrapper : NSObject // 封装C++的函数/类逻辑 + (NSInteger)calculateSumWithA:(NSInteger)a b:(NSInteger)b; @end// CPPWrapper.mm(Objective-C++实现) #import "CPPWrapper.h" #include "your_cpp_core.h" // 引入你的C++核心代码头文件 @implementation CPPWrapper + (NSInteger)calculateSumWithA:(NSInteger)a b:(NSInteger)b { // 直接调用C++函数 return static_cast<NSInteger>(your_cpp_sum(a, b)); } @end - 在iosMain中配置Objective-C互操作
在KMM项目的src/nativeInterop/cinterop目录下创建objcppinterop.def文件,内容指定要桥接的头文件:
然后在项目的headers = CPPWrapper.h headerFilter = *.hbuild.gradle.kts中配置interop:kotlin { ios { compilations.main.cinterops { create("objcppinterop") { defFile = file("src/nativeInterop/cinterop/objcppinterop.def") // 若头文件不在默认路径,添加include路径 compilerOpts("-I${projectDir}/path/to/objcpp/headers") } } } } - 在iosMain中调用
同步gradle后,就可以在iosMain的Kotlin代码中直接调用封装好的Objective-C方法:import objcppinterop.CPPWrapper fun calculateSum(a: Int, b: Int): Int { return CPPWrapper.calculateSumWithA(a, b).toInt() }
方法二:通过C Interop直接调用(extern "C"导出C++接口)
如果你的C逻辑以函数为主,可以用extern "C"将C接口导出为C风格,让Kotlin/Native直接通过C interop调用,更轻量:
- 导出C++接口为C风格
创建桥接头文件,用extern "C"包裹要暴露的函数:
实现文件中调用你的C++核心代码:// cpp_c_bridge.h #ifdef __cplusplus extern "C" { #endif int cpp_c_sum(int a, int b); #ifdef __cplusplus } #endif// cpp_c_bridge.cpp #include "cpp_c_bridge.h" #include "your_cpp_core.h" int cpp_c_sum(int a, int b) { return your_cpp_sum(a, b); } - 配置Kotlin/Native的C Interop
在src/nativeInterop/cinterop下创建cppcinterop.def文件:
同样在headers = cpp_c_bridge.h compilerOpts = -I/path/to/your/cpp/headers linkerOpts = -L/path/to/your/cpp/library -lyour_cpp_static_libbuild.gradle.kts中配置interop:kotlin { ios { compilations.main.cinterops { create("cppcinterop") { defFile = file("src/nativeInterop/cinterop/cppcinterop.def") } } } } - 在iosMain中调用
导入生成的Kotlin绑定后直接调用:import cppcinterop.cpp_c_sum fun sum(a: Int, b: Int): Int { return cpp_c_sum(a, b) }
注意事项
- 复杂C类推荐用第一种方法,Objective-C可以更好地封装类实例、成员函数和生命周期管理;简单函数接口优先第二种方法,更高效。
- 确保C++编译产物(静态库/动态库)被正确链接到iOS目标,比如通过
linkerOpts指定库路径和名称,或在CocoaPods配置中引入依赖。 - 使用C interop时,需手动管理C++返回的指针内存,避免内存泄漏,可借助Kotlin的
memScoped等工具处理。
内容的提问来源于stack exchange,提问作者user48646
相关产品推荐
相关产品推荐

