flipper-io / flipper

Flipper is a development platform that can be controlled from any programming language.
https://www.flipper.io/
Apache License 2.0
70 stars 15 forks source link

Implemented Java class/C struct translation and refactored drivers. #57

Closed nicholastmosher closed 8 years ago

nicholastmosher commented 8 years ago

JNA has very well-built facilities for creating "Structure" classes which can then be passed into/out of bindings that equate to any type of reference parameter. However, there are several overhead requirements to JNA's process that make the translation cumbersome and non-trivial. I've created a subclass of JNA's Structure class (also called "Structure", but in the io.flipper.java package) which helps to alleviate several of these difficulties.

Here's a brief illustration of using a vanilla JNA Structure versus using my extended Flipper Structure:

public class MyStruct extends com.sun.jna.Structure {
    int a;
    int b;
    protected List getFieldOrder() {
        return Arrays.asList(new String[]{"a", "b"});
    }
}

Versus:

public class MyStruct extends io.flipper.java.Structure {
    int a;
    int b;
}

By creating a custom Structure class, we 1) have fine-grained control over the exposure of Structure methods, 2) can override Structure methods for custom functionality, and 3) include Structure inside of the io.flipper.java package where it's easily visible and accessible to users.

To use a Structure in a driver, simply pass it in as a parameter to an overloaded function that accepts it:

MyStruct struct = new MyStruct();
flipper.usb.pull(struct);
System.out.println("Got a=" + struct.a + " from usb!");

Note that the Java representation of a Structure must be aligned correctly in terms of the packing for the native system, and misalignment will obviously cause misinterpretation of data.