Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I reference C++ code from KMM iosMain?

I'm considering implementing KMM in my project. I was able to reference C++ code via JNI in androidMain.

However, I was unable to use external fun in iosMain because it uses Kotlin/Native. In existing iOS projects, it was possible to call Objective-C++ from Swift and reference C++ code from Objective-C++.

Is there a way to reference C++ code from iosMain?

like image 330
user48646 Avatar asked Feb 12 '26 17:02

user48646


1 Answers

I made an effort to resolve the problem.

The first prerequisite is how the XCFramework is created. C++ cannot be referenced directly in Swift. Therefore, to create the XCFramework, it is necessary to wrap C++ in Objective-C++.

Next, create a def file. Suppose we have a Bridge.XCFramework that wraps C++ with Objective-C++. We name this def file framework.def.

language = Objective-C
modules = Bridge
package = Bridge

Modify Build.gradle.kts. Make sure to load the corresponding framework for each architecture.

listOf(
    iosX64(),
    iosArm64(),
    iosSimulatorArm64()
).forEach {
    it.binaries.framework {
        baseName = "shared"
        xcf.add(this)
    }

    val myFrameworkCompilerLinkerOptssim = listOf(
        "-framework",
        "Bridge",
        "-F/{Path}/Bridge.xcframework/ios-arm64_x86_64-simulator"
    )
    val myFrameworkCompilerLinkerOpts = listOf(
        "-framework",
        "Bridge",
        "-F/{Path}/Bridge.xcframework/ios-arm64"
    )

    it.compilations.getByName("main") {
        val ZipArchive by cinterops.creating {
            defFile("src/nativeInterop/cinterop/framework.def")

            when (it) {
                iosArm64() -> compilerOpts(myFrameworkCompilerLinkerOpts)
                iosSimulatorArm64() -> compilerOpts(myFrameworkCompilerLinkerOptssim)
                else -> compilerOpts(myFrameworkCompilerLinkerOptssim)
            }
        }

        it.binaries.all {
            when (it) {
                iosArm64() -> linkerOpts(myFrameworkCompilerLinkerOpts)
                iosSimulatorArm64() -> linkerOpts(myFrameworkCompilerLinkerOptssim)
                else -> linkerOpts(myFrameworkCompilerLinkerOptssim)
            }
        }
    }
}

Synchronize Build.gradle.kts when done. import is the name of the framework.

import Bridge.*

Now you can call C++ wrapped in Objective-C++ from iOSMain.

like image 147
user48646 Avatar answered Feb 15 '26 07:02

user48646



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!