Java调用Golang生成的动态库(DLL,SO)

作者: adm 分类: go,java 发布时间: 2022-08-30

环境准备
gcc -v
1
如果提示命令没有找到,那么你的电脑里没有gcc,去安装一个,gcc官网:https://gcc.gnu.org/
如果没安装过gcc的朋友可以直接安装win-build,可以帮你快速安装官网:https://www.mingw-w64.org/downloads/#mingw-builds

编写程序

package main

import "C"

//export Sum
func Sum(a int, b int) int {
	return a + b
}

//export Cut
func Cut(a int, b int) int {
	return a - b
}

//export Hello
func Hello(msg string) *C.char {
	return C.CString("hello : " + msg)
}

func main() {

}

注意:即使要编译成动态库,也必须要有main函数。上面的导入“C”必须存在并且必须被注释//export Hello。

构建动态库
Windows动态库

go build -buildmode=c-shared -o libhello.dll libhello.go

执行以下命令生成DLL动态链接库:

Linux/Unix/macOS 动态库
执行如下命令生成 SO 动态库:

go build -buildmode=c-shared -o libhello.so .\libhello.go

java中调用
引用JNA

<dependency>
	<groupId>net.java.dev.jna</groupId>
	<artifactId>jna</artifactId>
	<version>4.5.2</version>
</dependency>

创建接口

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

public interface LibHello extends Library {
	LibHello INSTANCE = (LibHello) Native.loadLibrary("E:/resources/libhello", LibHello.class);

	int Sum(int a, int b);
	int Cut(int a, int b);
	String Hello(GoString.ByValue msg);
}

GoString

import com.sun.jna.Structure;

import java.util.ArrayList;
import java.util.List;

public class GoString extends Structure {

	public String str;
	public long length;

	public GoString() {
	}

	public GoString(String str) {
		this.str = str;
		this.length = str.length();
	}

	@Override
	protected List getFieldOrder() {
		List fields = new ArrayList<>();
		fields.add("str");
		fields.add("length");
		return fields;
	}

	public static class ByValue extends GoString implements Structure.ByValue {
		public ByValue() {
		}

		public ByValue(String str) {
			super(str);
		}
	}


	public static class ByReference extends GoString implements Structure.ByReference {
		public ByReference() {
		}

		public ByReference(String str) {
			super(str);
		}
	}
}

调用接口

public class App {
	public static void main(String[] args) {
		System.out.println(LibHello.INSTANCE.Sum(222, 333));
		System.out.println(LibHello.INSTANCE.Cut(666, 333));
		System.out.println(LibHello.INSTANCE.Hello(new GoString.ByValue("Go")));
	}
}

运行结果:

555
333
hello : Go

Process finished with exit code 0

如果觉得我的文章对您有用,请随意赞赏。您的支持将鼓励我继续创作!