Examples to explain how to use go:linkname

藏色散人
Release: 2021-12-17 14:32:56
forward
2200 people have browsed it

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
Copy after login

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()
    }
}
Copy after login

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
Copy after login

go mod initialize project directory

$go mod init demo
Copy after login

Create function signature pkg and function body pkg

$mkdir hello
$mkdir link
Copy after login

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!")
}
Copy after login

Execute code

$cd demo
vim demo.go
package main

import (
    "demo/hello"
)

func main() {
    hello.Hello()
}
Copy after login

Compile and run

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

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!
Copy after login

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!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!