Problem using exported function type with C types as parameters
EDIT: changed the title to better reflect the issue thanks to @Not_a_Golfer
I have been experimenting with Go and cannot figure out this problem.
The following works great if contained in the main package:
// Define a callback-function type, and define an invoker for it type Callback func(i C.int, d C.double) func Invoke(cb Callback, i C.int, d C.double) { cb(i, d) } //... then define my callback and pass it into the invoker func foo(i C.int, d C.double) { fmt.Printf("i %d d %f\n", i, d) } func main() { Invoke(foo, 2, 2.2) }
But when I define type Callback
and Invoke
in a package, import the package in main and call mypkg.Invoker(foo, 2, 2.2)
. I am getting the following build error:
src/hello/hello.go:9: cannot convert foo (type func(C.int, C.double)) to type mypkg.Callback
Edit: Here's the main code for the welcome package. I structured everything so that I can use the command go
to build / install:
package main import "C" import "mypkg" import "fmt" func foo(i C.int, d C.double) { fmt.Printf("i %d d %f\n", i, d) } func main() { mypkg.Invoke( mypkg.Callback(foo), 2, 2.2 ) }
Does anyone know if there is anything special for a type exported from a package? I use C types in the arguments because it will eventually be a wrapper around the C library, and I just wanted to make sure that the C types were not part of the problem my callback matched to the callback type.
Here is the package code:
package mypkg import "C" import "fmt" type Callback func(i C.int, d C.double) func Invoke(cb Callback, i C.int, d C.double) { fmt.Println("Calling cb\n") cb( i, d ) }
source to share
They are actually different types!
Change your code to:
package main
import "C"
import "mypkg"
func main() {
a := 1
mypkg.Inc(C.int(a))
}
my package:
package mypkg
import "C"
func Inc(a C.int) C.int {
return a + 1
}
Compiling the first package will give an error:. /test.go:9: cannot use C.int (a) (type C.int) as type mypkg.C.int in argument mypkg.Inc
source to share