登录
首页 >  Golang >  Go问答

如何使用 Java 原生接口从 Java 调用 Go 函数?

来源:Golang技术栈

时间:2023-04-15 14:05:23 450浏览 收藏

珍惜时间,勤奋学习!今天给大家带来《如何使用 Java 原生接口从 Java 调用 Go 函数?》,正文内容主要涉及到golang等等,如果你正在学习Golang,或者是对Golang有疑问,欢迎大家关注我!后面我会持续更新相关内容的,希望都能帮到正在学习的大家!

问题内容

在 Java 中可以通过JNA接口调用 C 方法。如何使用 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
}

正确答案

查看有关Go 共享库的文档后:

可以从 Java Spring Batch 集成 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
}

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

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);
  }
}

之后,从主 Java 类执行。结果:

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 ', 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 函数?》的详细内容,更多关于golang的资料请关注golang学习网公众号!

声明:本文转载于:Golang技术栈 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>
评论列表