本文由golang教程栏目给大家介绍go:linkname怎么用,希望对需要的朋友有所帮助!
go:linkname的用法
在go语言的源码中,会发现很多,代码只有函数签名,却看不到函数体,如
// src/os/proc.go 68行func runtime,beforeexit() // implemented in runtime此处我们只看到函数签名,却看不到函数体,全局搜了一把,发现它的函数体却定义在src/runtime/proc.go中
// os,beforeexit is called from os.exit(0).//go:linkname os,beforeexit os.runtime,beforeexitfunc os,beforeexit() { if raceenabled { racefini() }}它是通过go:linkname把函数签名和函数体连接在一起的。这样的话我们在代码中,可以这样实现么?既然库函数中,可以这么用,那我们自己的代码结构中是不也可以这么用?以下通过实验的方法,一步一步的实现这样的用法创建项目目录
$mkdir demo && cd demogo mod初始化项目目录
$go mod init demo创建函数签名pkg和函数体pkg
$mkdir hello$mkdir link编写测试代码
$cd hello// 函数签名$vim hello.gopackage helloimport ( , demo/link)func hello()// 函数体$vim link.gopackage linkimport , unsafe//go:linkname helloworld demo/hello.hellofunc helloworld() { println(hello world!)}执行代码
$cd demovim demo.gopackage mainimport ( demo/hello)func main() { hello.hello()}编译运行
go run demo.go# demo/hellohello/hello.go:7:6: missing function body在hello文件夹下添加aa.s的汇编文件标示,便可以借助编译执行
$cd hello && touch aa.s$go run demo.gohello world!