Call Kotlin from Python using shared DLL

Submitted by Dickens A S on Mon, 04/20/2020 - 11:44

Kotlin Shared DLL and Python Extension

GitHub: https://github.com/dickensas/kotlindll

Compile and Execute from MSYS2 or Cygwin with python development C header files

Demo Output

Python Output

Python Code which calls the module

import myModule
myModule.helloworld()

setup.py - extension definition

from distutils.core import setup, Extension
setup(name = 'myModule', version = '1.0',  \
   ext_modules = [Extension('myModule', ['mymodule.c'], library_dirs=["./"], libraries=['myext'])])

mymodule.c - code which defines the python extension function and invokes Kotlin function via DLL

#include <Python.h>
#include "libmyext_api.h"

static PyObject* helloworld(PyObject* self, PyObject* args) {
	libmyext_ExportedSymbols* lib = libmyext_symbols();
	printf("%s",lib->kotlin.root.example.someLibraryMethod());
	return Py_None;
}

static PyMethodDef myMethods[] = { { "helloworld", helloworld, METH_NOARGS,
		"Prints Hello World" }, { NULL, NULL, 0, NULL } };

static struct PyModuleDef myModule = { PyModuleDef_HEAD_INIT, "myModule",
		"Test Module", -1, myMethods };

PyMODINIT_FUNC PyInit_myModule(void) {
	return PyModule_Create(&myModule);
}

libmyext_api.h is auto generated by kotlin-native gradle

hello.kt - The Kotlin code which gets compiled to a shared DLL

package example

fun someLibraryMethod(): String? {
    return "Hello from Kotlin DLL"
}

val globalString = "A global String"

The C Bridge (inside mymodule.c)

libmyext_ExportedSymbols* lib = libmyext_symbols();
printf("%s",lib->kotlin.root.example.someLibraryMethod());

Technically the DLL function someLibraryMethod is invoked in C - the mymodule.c acts as a stub for python 

Indirectly we are making a call from python to C to DLL

 

For embedded Python directly into Kotlin - Refer this article - Enbed python in kotlin native

 

 

Add new comment