是否可以在 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.
关于pointers - 如何在go中获取函数的地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41043462/