Kotlin interop with Python (via C)

I have some Kotlin code I’d like to re-use from a Python program/script. Is the best way to do this by using Kotlin Native to create a C library and then use that library from Python? I’ve looked at the Kotlin Native documentation on Github - and it looks like this should be possible.

  1. is this the best approach?
  2. if so are there some examples/documentation?

Hi there,

There is a sample code in the kotlin-native repository. Please note that the example is old and not up-to-date but you can see how it is supposed to work which is by creating a dynamic library (doc here) and then use the generated C headers to create a C bridge between Python and Kotlin.

This is not the best approach but it is the only one for now. As Python interop is clearly not one of the main use cases JetBrains is focused on I think you are on your own with this documentation-wise.

hello aynum,

I don’t know if that can help you, you can call python a kotlin …

Another solution is to try GraalVM polyglot option. Never tried it myself, but it looks really promising.

We had the same need, which seems pretty natural (backend in Kotlin, user scripts in Python), and the most mature solution we found (not perfect yet though) is JPype: JPype1 · PyPI

I know the thread is nearly 3 years old at this point, but if anyone still needs this I’ve written a Gradle Plugin for Kotlin/Multiplatform to target the Python C API. It currently only supports Python 3.10 on x86-64 however, as I don’t have a good way of building Windows targets for any version other than relying on msys2.

1 Like