javagojnamultiple-return-values

How to write interface for a go function with multi return values with JNA


I'm trying to export some Go functions and call them in Java, with JNA, but I don't know how to define the interface in Java for a Go function with multiple return values.

Say the Go function is:

//export generateKeys
func generateKeys() (privateKey, publicKey []byte) {
    return .....
}

The return values has two items, but in Java, there is only one return value allowed.

What can I do?


Solution

  • cgo creates a dedicated C struct for multiple return values, with the individual return values as struct elements.

    In your example, cgo would generate

    /* Return type for generateKeys */
    struct generateKeys_return {
        GoSlice r0; /* privateKey */
        GoSlice r1; /* publicKey */
    };
    

    and the function would have a different signature, which you then use via JNA

    extern struct generateKeys_return generateKeys();
    

    In your JNA definition, you'd then resemble the structure using JNA concepts (untested code):

    public interface Generator extends Library {
    
            public class GoSlice extends Structure {
                public Pointer data;
                public long len;
                public long cap;
                protected List getFieldOrder(){
                    return Arrays.asList(new String[]{"data","len","cap"});
                }
            }
    
            public class GenerateKeysResult extends Structure {
                public GoSlice privateKey;
                public GoSlice publicKey;
                protected List getFieldOrder(){
                    return Arrays.asList(new String[]{"privateKey","publicKey"});
                }
            }
    
            public GenerateKeysResult generateKeys();
    }