【转】【GO】9.go:linkname

    xiaoxiao2023-11-12  158

    go:linkname的官方说明

    //go:linkname localname importpath.name The //go:linkname directive instructs the compiler to use “importpath.name” as the object file symbol name for the variable or function declared as “localname” in the source code. Because this directive can subvert the type system and package modularity, it is only enabled in files that have imported "unsafe".

    这个指令告诉编译器为当前源文件中私有函数或者变量在编译时链接到指定的方法或变量。因为这个指令破坏了类型系统和包的模块化,因此在使用时必须导入unsafe包,所以可以看到runtime/time.go文件是有导入unsafe包的。 我们看到go:linkname的格式,这里localname自然对应timeSleep, importpath.name就对应time.Sleep,但为什么要这么做呢? 我们知道time.Sleep在time包里,是可导出,而timeSleep在runtime包里面,是不可导出了,那么go:linkname的意义在于让time可以调用runtime中原本不可导出的函数,有点hack,举个栗子:

    目录结构如下

    ➜ demo git:(master) ✗ tree . ├── linkname │ └── a.go ├── main.go └── outer └── world.go

    文件内容 a.go

    package linkname import _ "unsafe" //go:linkname hello examples/demo/outer.World func hello() { println("hello,world!") }

    world.go

    package outer import ( _ "examples/demo/linkname" ) func World()

    main.go

    package main import ( "examples/demo/outer" ) func main() { outer.World() }

    运行如下:

    # examples/demo/outer outer/world.go:7:6: missing function body

    难道理解错了,这是因为go build默认加会加上-complete参数,这个参数检查到World()没有方法体,在outer文件夹中增加一个空的.s文件即可绕过这个限制

    ➜ demo git:(master) ✗ tree . ├── linkname │ └── a.go ├── main.go └── outer ├── i.s └── world.go

    输出如下:

    hello,world!

     

    最新回复(0)