java 调用 go,如何使用Java本机接口从Java调用go函数?

这篇博客介绍了如何在Java中通过Java Native Access (JNA) 接口调用Go语言编写的C共享库。首先,展示了Go函数的定义,然后通过`go build -buildmode=c-shared`命令生成C共享库。接着,创建Java类并使用JNA加载库文件,最后在Java中调用Go函数并输出结果。整个过程实现了Java与Go之间的交互,为跨语言集成提供了实例。
摘要由CSDN通过智能技术生成

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

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

Golang function:

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

This generates the binary files:

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

Finally, create the JNA class:

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

}

}

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 ', or link it with '-z noexecstack'.

Java says: about to call Go ..

Go says: adding 30 and 12

Java says: result is 42

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值