A Python native extension written in Kotlin Native

Overview

Kotlin Python Ext

This is a proof of concept for a Python extension in Kotlin.
It is recommended to read the Official Python C API Documentation before getting started with this.
If you have any other questions, feel free to contact me on Discord at Martmists#3740.

Usage

This is going to be a messy readme since I'll be cramming in everything I can without a good structure, feel free to PR a better one.

To start off you'll need to make a module definition:

val moduleDef = makeModule(
    km_name = "my_module",
)

then, in your initializer:

fun createPyKtModule(): PyObjectT {
    val obj = PyModule_Create2(moduleDef, PYTHON_API_VERSION)
    
    return obj
}

Now you can import your module! To create a static function, you need to create a function first:

val helloFunc = staticCFunction { self: PyObjectT, args: PyObjectT ->
    println("Hello from Kotlin!")
    Py_None.incref()
}

Then we need a function definition:

val helloDef = helloFunc.pydef(
    "hello",  // function name
    "A simple function to say hello from Kotlin", // docstring
    METH_NOARGS,  // flags
)

Now we can add our function to our module:

val moduleDef = makeModule(
    km_name = "my_module",
    km_methods= listOf(
        helloDef,
    ),
)

Next up are classes! To create a class, you need to create a PyType:

class MyKotlinImpl {
    val n: Int = 0
    fun increment() {
        println(n++)
    }
}

val initImpl = staticCFunction { self: PyObjectT, args: PyObjectT, kwargs: PyObjectT ->
    // These generally work with StableRefs, and the default free implementation takes care of these.
    
    val selfObj: CPointer<KtPyObject> = self?.reinterpret() ?: return@staticCFunction -1
    
    val instance = MyKotlinImpl()  // initialize here, you can take parameters from args/kwargs using python C API if needed
    
    val ref = StableRef.create(instance)
    selfObj.pointed.ktObject = ref.asCPointer()
    return@staticCFunction 0
}

val myPyType = makePyType<MyKotlinImpl>(
    ktp_init=initImpl  // This is usually the only required field
)

Then we can add this to our module:

fun createPyKtModule(): PyObjectT {
    val obj = PyModule_Create2(moduleDef, PYTHON_API_VERSION)

    if (PyType_Ready(myPyType.ptr) < 0) {
        // An error occurred
        return null
    } else {
        // The class works, so add it to the module
        PyModule_AddType(obj, myPyType.ptr)
    }

    return obj
}

Utilities

There's a couple functions that are generally useful when working with the Python C API, such as reference counting:

fun doSomething(arg: PyObjectT) {
    PyObject_Print(arg.incref())
}

fun freeOtherThing() {
    this.arg.decref()
}

Other utilities are present in this repo, specifically Configurable.
Configurable allows you to define properties that get converted between kotlin and python automatically, though by default this only supports primitives and strings.
To make a class extend configurable:

class MyConfigurableType: Configurable() {
    var prop by attribute("prop", true)  // second arg is default value, avoid nulls!
    
    fun thing() {
        println("prop: $prop")
    }
}

val myConfPyType = makePyType<MyConfigurableType>(
    ktp_base=PyType_Configurable.ptr,  // Extend Configurable (or a class that extends Configurable)
    ...
)
You might also like...
A full-stack application showing the power 💪 of KOTLIN. Entire android app + backend Apis written in Kotlin 🔥
A full-stack application showing the power 💪 of KOTLIN. Entire android app + backend Apis written in Kotlin 🔥

Gamebaaz 🎮 A full-stack application showing the power 💪 of KOTLIN. Entire android app + backend Apis written in Kotlin 🔥 Android Backend Jetpack Co

A showcase music app for Android entirely written using Kotlin language

Bandhook Kotlin This project is a small replica of the app I developed some time ago. Bandhook can still be found on Play Store At the moment it will

Utility Android app for generating color palettes of images using the Palette library. Written in Kotlin.
Utility Android app for generating color palettes of images using the Palette library. Written in Kotlin.

Palette Helper is a simple utility app made to generate color palettes of images using Google's fantastic Palette library. It's mostly a for-fun pet p

Utility Android app for generating color palettes of images using the Palette library. Written in Kotlin.
Utility Android app for generating color palettes of images using the Palette library. Written in Kotlin.

Palette Helper is a simple utility app made to generate color palettes of images using Google's fantastic Palette library. It's mostly a for-fun pet p

Episodie is a TV show time tracker app with unusual design written in kotlin and clean architecture approach. Get to know how much time you spent watching tv shows.
Episodie is a TV show time tracker app with unusual design written in kotlin and clean architecture approach. Get to know how much time you spent watching tv shows.

Episodie Episodie is a TV show time tracker app with unusual design. Get to know how much time you spent watching tv shows. Track easily overall progr

KataContacts written in Kotlin. The main goal is to practice Clean Architecture Development

KataContacts written in Kotlin We are here to practice Clean Architecture Development. Clean Architecture is a way of structuring code. We are going t

A simple android Twitter client written in Kotlin
A simple android Twitter client written in Kotlin

Blum Blum is an unofficial, simple, fast Twitter client written in Kotlin. This project is a complete rewrite of the Java version. Screenshot Build To

📚  Sample Android Components Architecture on a modular word focused on the scalability, testability and maintainability written in Kotlin, following best practices using Jetpack.
📚 Sample Android Components Architecture on a modular word focused on the scalability, testability and maintainability written in Kotlin, following best practices using Jetpack.

Android Components Architecture in a Modular Word Android Components Architecture in a Modular Word is a sample project that presents modern, 2020 app

Mobile client for official Nextcloud News App written as Kotlin Multiplatform Project
Mobile client for official Nextcloud News App written as Kotlin Multiplatform Project

Newsout Android and iOS mobile client for Nextcloud news App. The Android client is already available to download in the Play Store. F-Droid and Apple

Owner
Martmists
Backend dev. Proficient in Python, Fluent in Kotlin, C++ and more
Martmists
This is an example for running a Python library (mishkal) in Android using chaquopy

chaquopy-mishkal This is an example for running a Python library (mishkal) in Android using chaquopy Code All the code that has been added to run the

Mehdi Nassim KHODJA 2 Oct 10, 2022
Bandicoot an open-source python toolbox to analyze mobile phone metadata

bandicoot is Python toolbox to analyze mobile phone metadata. It provides a complete, easy-to-use environment for data-scientist to analyze mobile phone metadata. With only a few lines of code, load your datasets, visualize the data, perform analyses, and export the results.

Computational Privacy Group @ Imperial College London 231 Sep 12, 2022
A PyCharm plugin that implements inlay parameter and type annotation hints for Python.

Python Inlay Params Quick Installation Using IDE built-in plugin system: Settings/Preferences > Plugins > Marketplace > Search for "Python Inlay Param

Daniil Kovalenko 19 Dec 5, 2022
Burp extension to scan Log4Shell (CVE-2021-44228) vulnerability pre and post auth

Log4J Scanner Burp extension to scan Log4Shell (CVE-2021-44228) vulnerability pre and post auth. Disclaimer I am not responsible for your actions, bur

Dexter0us 94 Nov 22, 2022
F-Droid Privilege Extension that works with Shizuku (rootless)

F-Droid Shizuku Privileged Extension This is a port of the official F-Droid Privileged Extension to Shizuku, an app that makes it easy to grant apps A

Davide Depau 4 Nov 18, 2022
ADX provides extension functions and lint.

ADX: Android development extensions Overview ADX provides extension functions and lint. Installation ADX implementation "com.github.wada811.adx:adx:$v

wada811 2 Nov 7, 2022
📲💬 react-native-fontext is a lightweight library to integrate fonts in your React Native application that works seamlessly in android and iOS devices.

React Native Fontext react-native-fontext is a lightweight library to integrate fonts in your React Native application that works seamlessly in androi

mroads 9 Dec 3, 2021
Native-loader - Safely load native libraries in Java

Native Loader ??️ Safe native loading in Java based off of the native-loader use

Mixtape 1 Oct 19, 2022
React-native-user-interface - Change React Native userinterface at runtime

react-native-user-interface change RN userinterface at runtime. Installation npm

Ahmed Eid 0 Jan 11, 2022
Matomo wrapper for React-Native. Supports Android and iOS. Fixed issues for native platforms build that are present in the official package.

@mccsoft/react-native-matomo Matomo wrapper for React-Native. Supports Android and iOS. Fixed issues for native platforms build that are present in th

MCC Soft 4 Dec 29, 2022