Kotlin multiplatform mobile and C interop

I am currently developing an Android/iOS app that will use some older non platfrom specific libs written in C++ and exposed with extern C for usage in cinterop.

I have created the .klib and it runs just fine when compiled as .kexe. The problem is that i can not find the way how to include this .klib in Kotlin multipartform mobile project. I would want it to be accessible from commonMain so i could add some additional logic and bussines stuff above it.

I went trough posts like this:

But i cant get to import my “custom” lib in commonMain in any way. It is plain C code no system or platform specific calls.

Is this possible? What am I missing?

1 Like

No it’s not possible. You can only call C-code from kotlin-native (or from kotlin-jvm using something like jni). It’s not something you can do from common code or js.

1 Like

But isn’t he doing something like that in the above given post? At least for iOS.

Is it possible to do it via Kotlin Native? I know that I will only need Android/iOS so no JS and stuff.

I would be happy if anyone can correct me but right now it is not possible to share C-interop code between native and jvm. You can share that code between different native targets though (eg. macos and ios).

I’m not an expert on this but my understanding is that the klib format is used not only for native libraries but also for any kind of kotlin multiplatform library. That means that it can contain both common and native parts.

2 Likes

From my understanding it should be possible to some extent, especially for plain C code without any platform specific dependencies.

The main goal for me would be to avoid using JNI and any other kind of unnecessary wrappers. So only one C code for both iOS / Android.

I have already tested this with Flutter and Dart:ffi and works as charm, but there you are locking yourself into Dart/Flutter environment.

It would be nice if more of you could join the discussion and present your point of view on this topic.

Below is the same problem that should “work” on iOS, but i didn’t test it yet and don’t know how to make it work on Android: android - Access C/C++ lib from a multiplatform kotlin project - Stack Overflow

If no direct solution is possible, maybe the best way would be to export .aar and .framework from .klib? Just a thought.