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

如何使用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?

图片转代码服务由CSDN问答提供 功能建议

我正在尝试导出一些Go函数并使用 JNA ,但我不知道如何在Java中为具有多个返回值的Go函数定义接口。

说Go函数是:

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

返回值有两个项目,但是在Java中,只允许一个返回值。

我该怎么办?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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();
    }
    
    点赞 打赏 评论

相关推荐 更多相似问题