Tarion
Tarion

Reputation: 17174

How to get the address of a function in 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.

Upvotes: 2

Views: 7759

Answers (4)

ceving
ceving

Reputation: 23871

You can do this:

myFunction := func() {}
fmt.Println(&myFunction)

Upvotes: -1

Egor
Egor

Reputation: 81

You can get address of function use function 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 )
  }

Upvotes: 1

You may get the address of a Go function like this:

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

Upvotes: 4

I159
I159

Reputation: 31199

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.

Upvotes: 10

Related Questions