0

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?

Freewind
  • 193,756
  • 157
  • 432
  • 708
  • You'll first want to figure out how you could call that from C, then translate that to work with JNA. I have no idea how Go's compiler handles multiple return values, for example. – cbr Apr 21 '18 at 15:13

1 Answers1

1

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();
}
fhe
  • 6,099
  • 1
  • 41
  • 44
  • Finally I make it work inspired of your answer, thanks. There is something notable, we can't return `[]type` in Go functions, instead, we should use `unsafe.Pointer`, otherwise cgo will report error like "It exports a go pointer" – Freewind Apr 22 '18 at 10:14
  • The working demo is here: . There probably be something wrong since I don't how to free the pointers where the document says it needs to – Freewind Apr 22 '18 at 10:15