du9843 2018-04-21 14:51
浏览 244
已采纳

如何使用JNA为具有多个返回值的go函数编写接口

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?

  • 写回答

1条回答 默认 最新

  • duanchique1196 2018-04-21 15:19
    关注

    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();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?