title: passing function pointer to the C code using cgo
body: <p>Starting from Go v1.6 cgo changed the rules of passing pointers to the C code <a href="https://github.com/golang/go/issues/12416" rel="noreferrer">golang/go#12416</a>.
  The example of invoking a dynamic Go callback from C code from the wiki  doesn't work anymore.</p>
  
  <pre><code>package main
  
  import (
      "fmt"
      "unsafe"
  )
  
  /*
     extern void go_callback_int(void* foo, int p1);
  
     // normally you will have to define function or variables
     // in another separate C file to avoid the multiple definition
     // errors, however, using "static inline" is a nice workaround
     // for simple functions like this one.
     static inline void CallMyFunction(void* pfoo) {
         go_callback_int(pfoo, 5);
         }
  */
  import "C"
  
  //export go_callback_int
  func go_callback_int(pfoo unsafe.Pointer, p1 C.int) {
      foo := *(*func(C.int))(pfoo)
      foo(p1)
  }
  
  func MyCallback(x C.int) {
      fmt.Println("callback with", x)
  }
  
  // we store it in a global variable so that the garbage collector
  // doesn't clean up the memory for any temporary variables created.
  var MyCallbackFunc = MyCallback
  
  func Example() {
      C.CallMyFunction(unsafe.Pointer(&amp;MyCallbackFunc))
  }
  
  func main() {
      Example()
  }
  </code></pre>
  
  <p>The output looks like this:</p>
  
  <pre><code>panic: runtime error: cgo argument has Go pointer to Go pointer
  </code></pre>
  
  <p>What is the proper way to do this today? Preferably without hacks like hiding pointer from the language by converting it into uintptr_t.</p>