如何在go中获取函数的地址?

How to get the address of a function in go?

是否可以在 Go 中获取函数引用的地址?

类似

func myFunction() {
}

// ...

unsafe.Pointer(&myFunction)

只是这样不行。我猜这不可能,但我还没有找到任何证据。

编辑:背景

我的问题背景来自处理CGO和C函数指针。 这有效:

/*
void go_myFunction();

typedef void (*myFunction_f)();

myFunction_f pMyFunction;
*/
import "C"

//export go_myFunction
func go_myFunction() {
// ...
}

func SetupFp() {
  C.pMyFunction = (*[0]byte)(unsafe.Pointer(C.go_myFunction))
}

我还知道文档指出将指针传递给 go 函数是行不通的。但是上面的代码似乎离它不远。我只是想知道是否可以以某种方式跳过导出步骤。

function Go 中的类型不可寻址且不可比较,因为:

Function pointers denote the code of the function. And the code of an anonymous function created by function literal is only stored once in memory, no matter how many times the code that returns the anonymous function value runs.

如果您需要比较一个函数的地址,您可以使用 reflect.Pointer 来完成。但无论如何,这个操作比不可能更无意义,因为:

If v's Kind is Func, the returned pointer is an underlying code pointer, but not necessarily enough to identify a single function uniquely. The only guarantee is that the result is zero if and only if v is a nil func Value.

你可能会得到这样一个 Go 函数的地址:

package main

import (
    "fmt"
    "reflect"
)

func HelloWorld() {
    fmt.Println("Hello, world!")
}

func main() {
    var ptr uintptr = reflect.ValueOf(HelloWorld).Pointer()
    fmt.Printf("0x%x", ptr)
}

可以得到函数使用函数的地址 GetFuncAddr:

    package main

     import (
         "fmt"
         "unsafe"
         "reflect"
      )

     func HelloWorld() {
        fmt.Println("Hello, world!")
     }


     func GetFuncAddr(i interface{}) uintptr {
     type IHeader struct {
        typ  uintptr
        word uintptr
      }
    
    return (*IHeader)(unsafe.Pointer(&i)).word
    }

  func main() {
   tmp := HelloWorld
   ptr1 := *(*uintptr)(unsafe.Pointer(&tmp)) //Way 1

   ptr2 := GetFuncAddr(HelloWorld)  //Way 2
   fmt.Printf("0x%x = 0x%x", ptr1, ptr2)

   //Thits is not are functon addrress!!!
   BadPTR1 := reflect.ValueOf(HelloWorld).Pointer()
   BadPTR2 := **(**uintptr)(unsafe.Pointer(&tmp)) //dereferenced pointer
   fmt.Printf("\nBAD: 0x%x = 0x%x", BadPTR1 , BadPTR2 )
  }