Call C++ code from Kotlin Native using a C bridge code

Submitted by Dickens A S on Sun, 05/28/2023 - 15:04

This article explains how to call C++ code from Kotlin Native using a C Bridge

The purpose of C Bridge is to overcome the short comings of Kotlin Native which does not support C++ interop

Therefore we create a C library and call the C++ codes in that code and then the C code is linked to Kotlin Native code

Important Note: this is not JNI, this is Kotlin Native which directly becomes an EXE file

C++ code which std::string

std::string CppLib::Library::greeting() {
	return "Hello, World! From C++";
}
const char* CppLib::Library::copy(std::string str) {
	char* arr = new char[str.length() + 1];
	strcpy(arr, str.c_str());
	return arr;
}

C code which bridges the C++ code

#include <cstdlib>

#include "cpplib_c.h"
#include "cpplib.h"

#ifdef __cplusplus
extern "C" {
#endif

static CppLib::Library *lib = NULL;

void init() {
    if (lib == NULL) {
    	lib = new CppLib::Library();
    }
}
const char* greeting() {
	init();
	return lib->copy(lib->greeting());
}

The Kotlin native code

import kotlinx.cinterop.*
import cpplib.*

fun main(args: Array<String>) = memScoped {
	println(greeting()!!.toKString())
}

here copy is a code which reads the pointer and copies the value to another pointer so that from C/Kotlin we can directly consume the string

Thats All :)

Github Source code

Add new comment