go build 的plugin模式

go build 的plugin模式

-buildmode=plugin

​ Build the listed main packages, plus all packages that they

​ import, into a Go plugin. Packages not named main are ignored.

plugin模式可以将package main 构建成一个Go 插件,并且可以在运行时动态加载。

先写一段代码

package main

import "fmt"

// 方法名大写开头
func Hello() {
	fmt.Println("hello world")
}
go build -buildmode=plugin -o hello.so main.go

img

生成了一个.so文件。

执行file hello.so

hello.so: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, BuildID[sha1]=b41942a8b584690d8aa7c63c4d41378426cf6747, not stripped

这里说,它是一个动态链接库。

如何调用呢?

package main

import (
	"fmt"
	"os"
	"plugin"
)

func main() {
	plug, err := plugin.Open("./hello.so")
	if err != nil {
		fmt.Println(err.Error())
		os.Exit(0)
	}
	fn,err :=plug.Lookup("Hello")
	if err != nil {
		fmt.Println(err.Error())
		os.Exit(0)
	}
	fn.(func())()  // 反射
}

​ Lookup会帮我们拿到那些变量或者方法,但是他们必须是可导出的。

然后就可以调用他们了。

posted @   博客是个啥?  阅读(306)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示