How can I import c++ code to commonMain (Kotlin/Multiplatform project)

Viewed 665

I want to implement a few use cases before migrating my business logic code from JAVA to Kotlin/Multiplatform. One of them is using c++ code. There is an option to use c++ code in Kotlin/Multiplatform project on commonMain level? Or I need to write a wrapper layer (like JNI) for each platform? Can I get some example code?

Many thanks!

1 Answers

Calling to C++ can be tricky. You'll need to have JNI on the JVM, and on native you'll need to wrap the C++ with C (or Objective-C), then use cinterop to make that available to the native Kotlin compiler. Then, in common, you'll need to write a common version of the logic, and have that implemented on each platform.

    Kotlin(common)
          |
         / \
        /   \
    Kt(jvm) Kt(native)
      /       \
    JNI       C/ObjC
    /           \
  C++           C++

There may eventually be direct C++ interop on native, but not sure when.

Related