如何使用Java本机接口从Java调用go函数? [英] How to call go function from java using Java native interface?

查看:226
本文介绍了如何使用Java本机接口从Java调用go函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以通过Java中的JNA接口调用C方法.我的问题是我如何使用Go达到相同的功能?

It is possible to call C methods through JNA interface in Java. My question is how I can reach the same functionality with Go?

package main

import "fmt"

import "C"

//export Add
func Add(x, y int) int {
    fmt.Printf("Go says: adding %v and %v\n", x, y)
    return x + y
}

推荐答案

在查看有关转到共享库的文档后,

After review of the documentation about Go Shared Libraries

可以在一个简短的示例下面集成Java Spring Batch中的调用Golang函数:

It is possible to integrate the call Golang functions from Java Spring Batch, below a short example:

Golang函数:

package main

import "fmt"

import "C"

//export Add
func Add(x, y int) int {
    fmt.Printf("Go says: adding %v and %v\n", x, y)
    return x + y
}

然后,执行命令以生成二进制文件:

After that, execute the command to generate the binary files:

go build -buildmode=c-shared -o bin/lib-cqm-transformer.so src/cqm_transformer.go

这将生成二进制文件:

ls -la bin/
total 2860
drwxrwxr-x 2 dmotta dmotta    4096 abr 23 01:13 .
drwxrwxr-x 5 dmotta dmotta    4096 abr 23 00:35 ..
-rw-r--r-- 1 root   root      1558 abr 23 01:13 lib-cqm-transformer.h
-rw-r--r-- 1 root   root   2915112 abr 23 01:13 lib-cqm-transformer.so

最后,创建JNA类:

package com.XX.XX.batch.engine.transformer;

import com.sun.jna.Library;
import com.sun.jna.Native;

public class GoEngineTransformerTest {
  static GoCqmTransformer GO_CQM_TRANSFORMER;
  static {
    String os = System.getProperty("os.name").toLowerCase();
    String libExtension;
    if (os.contains("mac os")) {
      libExtension = "dylib";
    } else if (os.contains("windows")) {
      libExtension = "dll";
    } else {
      libExtension = "so";
    }

    String pwd = System.getProperty("user.dir");
    String lib = pwd + "/golang/bin/lib-cqm-transformer." + libExtension;
    GO_CQM_TRANSFORMER = (GoCqmTransformer) Native.loadLibrary(lib, GoCqmTransformer.class);
  }

  public interface GoCqmTransformer extends Library {
    long Add(long x, long y);
  }

  public static void main(String[] args) {
    System.out.println("Java says: about to call Go ..");
    long total = GO_CQM_TRANSFORMER.Add(30, 12);
    System.out.println("Java says: result is " + total);
  }
}

然后,从Main Java类结果执行:

After that, execute from Main Java class, Results:

Java HotSpot(TM) 64-Bit Server VM warning: You have loaded library /tmp/jna1412558273325390219.tmp which might have disabled stack guard. The VM will try to fix the stack guard now.
It's highly recommended that you fix the library with 'execstack -c <libfile>', or link it with '-z noexecstack'.
Java says: about to call Go ..
Go says: adding 30 and 12
Java says: result is 42

这篇关于如何使用Java本机接口从Java调用go函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆