Home >Backend Development >Golang >Examples to explain how to use go:linkname

Examples to explain how to use go:linkname

藏色散人
藏色散人forward
2021-12-17 14:32:562425browse

This article is introduced by the golang tutorial column to introduce how to use go:linkname. I hope it will be helpful to friends in need!

Usage of go:linkname

In the source code of the go language, you will find a lot of codes that only have function signatures, but you cannot see the function body, such as :

// src/os/proc.go 68行
func runtime_beforeExit() // implemented in runtime

Here we only see the function signature, but not the function body. After searching globally, we found that its function body is defined in src/runtime/proc.go

// os_beforeExit is called from os.Exit(0).
//go:linkname os_beforeExit os.runtime_beforeExit
func os_beforeExit() {
    if raceenabled {
        racefini()
    }
}

It connects the function signature and function body through go:linkname. So can we implement this in code? Since this can be used in library functions, can it also be used in our own code structure? The following is an experimental method to implement such usage step by step
Create project directory

$mkdir demo && cd demo

go mod initialize project directory

$go mod init demo

Create function signature pkg and function body pkg

$mkdir hello
$mkdir link

Write test code

$cd hello
// 函数签名
$vim hello.go
package hello

import (
    _ "demo/link"
)

func Hello()

// 函数体
$vim link.go
package link

import _ "unsafe"

//go:linkname helloWorld demo/hello.Hello
func helloWorld() {
    println("hello world!")
}

Execute code

$cd demo
vim demo.go
package main

import (
    "demo/hello"
)

func main() {
    hello.Hello()
}

Compile and run

go run demo.go
# demo/hello
hello/hello.go:7:6: missing function body

Add the assembly file mark of aa.s in the hello folder, then you can compile and execute

$cd hello && touch aa.s
$go run demo.go
hello world!

The above is the detailed content of Examples to explain how to use go:linkname. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete