jyn: Simple Native Code Access in Jython

I had been wanting to mess around with native code access in Java for awhile. I’ve also been delving fairly deep into Jython, mostly out of necessity for RingMUD. So, I decided to combine these two ideas, and started work on a simple library similar to ctypes. Jython does not have a working ctypes implementation yet, but it is coming along. This was mostly for my own experimentation to learn a bit more Python as well as experiment with JNA (Java Native Access).

JNA is the much simpler alternative to JNI. In normal Java, you define an interface that corresponds to the function prototypes of the native library you want to access. You then create a new “instance” of the library by calling JNA’s special gateway method. From that point on, you can call the defined functions of the library.

The nice thing about Python is that it is a dynamic language. By overriding __getattr__ and friends, and using JNA’s reflection API, it becomes possible to have Jython lazily load the function references and call them in a much more intuitive way. The name of this simple library is jyn (No, no alcohol was involved in the creation of this library).

An example:

import jyn
lib = jyn.libc() #Load libc for Windows or Unix
printf = lib.printf
printf("Hello world! I am printing from Jython!\n")

jyn is not really suitable for production environments yet. The most glaring problem at the moment is that there is no argument checking. This means that passing wrong arguments to a native function will usually crash the JVM. I am definitely open to more experienced Python developers willing to improve the library.

jyn is intended mainly as a demonstration of what is possible with Java and Jython. The Java platform brings with it a large selection of powerful libraries, and Jython brings the dynamic power of Python. Combined, they are an unbeatable team.

Grab jyn from GitHub.