dongnunai3125 2016-12-08 15:49
浏览 461
已采纳

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

Is it possible to get the address of a function reference in Go?

Something like

func myFunction() {
}

// ...

unsafe.Pointer(&myFunction)

Just that is does not work that way. My guess it's not possible, but I did not found any proof yet.

Edit: Background

The background of my question comes from dealing with CGO and C Function pointers. This works:

/*
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))
}

I'm also aware that the documentation states that passing a pointer to a go function does not work. But the above code seems no to be that far from it. I was just wondering if one could somehow skip the export step.

  • 写回答

2条回答 默认 最新

  • duancenxiao0482 2016-12-08 17:36
    关注

    function type in Go is not addressable and not comparable because:

    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

    If you need to compare addresses of a functions you can do it with reflect.Pointer. But any way this operation is more senseless than impossible because:

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭