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

标签 pointers go cgo

是否可以在 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.

Original answer

如果你需要比较一个函数的地址,你可以使用 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/

相关文章:

c - 将结构定义的地址存储到指针中时是否会创建结构实例?

c - 指针未返回正确的值

go - 初始化多个资源并管理它们的生命周期

tcp - 在 Go 中超时 TCP 握手的惯用方法

go - 从 Mutating Admission Controller 中创建一个新的 Kubernetes 对象

go - 在 go 项目中使用 cgo 包含 libsodium 失败

c - c 中的网格和指针

c - 如何从传递给C函数的arguments(char *)获取字符串?

go - 你如何供应带有 Cgo 绑定(bind)的 Go 库?

c - 程序在尝试对结构的指针成员进行 malloc 时出现段错误