HomeiOS Developmentios - Can I reference C++ code from KMM iosMain?

ios – Can I reference C++ code from KMM iosMain?


it is potential to make use of the interoperability options of Kotlin/Native to name C++ capabilities out of your Kotlin code

to set it up:

  1. write C++ code in separate .cpp file + header file declaring the capabilities you need to name from Kotlin

instance:

mymodule.cpp

#embody "mymodule.h"

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

mymodule.h

#ifndef MYMODULE_H
#outline MYMODULE_H

extern "C" {
    int add(int a, int b);
}

#endif // MYMODULE_H
  1. create new Xcode venture + header file(declares C interface to C++ capabilities you need to use)

instance:

#ifndef MYMODULE_H
#outline MYMODULE_H

int add(int a, int b);

#endif // MYMODULE_H
  1. add C++ information to Xcode venture + compile as a part of the venture
  2. in KMM venture — create Kotlin/Native module + add C header file

instance:

kotlin {
    iosX64("ios") {
        compilations.essential {
            cinterops {
                mymodule {
                    defFile("mymodule.def")
                    includeDirs("src/native/embody")
                    compilerOpts("-I$projectDir/src/native/embody")
                }
            }
        }
    }
}
  1. in Kotlin code — use @CName to specify title of the C interface operate

instance:

import kotlinx.cinterop.*

@CName("add")
exterior enjoyable add(a: Int, b: Int): Int

enjoyable essential() {
    val sum = add(1, 2)
    println(sum)
}

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments