In the Go language, converting a `func` type to a `uintptr` type is a common operation, but the correct method is not to convert directly, because this may leading to some potential problems. The correct method is to use the `Pointer` function in the `unsafe` package to convert the `func` type value to the `unsafe.Pointer` type first, and then convert it to the `uintptr` type. This ensures the safety of type conversion and avoids unpredictable errors. Although this method requires the use of the `unsafe` package, under the right circumstances, it can effectively solve the problem of converting `Go func` to `uintptr`.
I need to pass and receive go functions in go code.
Due to the way system calls work in the go language, the type used for "passage" is uintptr
.
I have no choice but uintptr
since syscall.syscalln
accepts and returns this type.
What is the correct way to convert go func
to uintptr
?
I tried using it in the sandbox but I can't simply convert it.
package main import ( "fmt" "unsafe" ) func main() { var f MyFunc = SumInt fmt.Println(f(1, 2)) test(uintptr(f)) // Cannot convert an expression of the type 'MyFunc' to the type 'uintptr' test(uintptr(unsafe.Pointer(f))) // Cannot convert an expression of the type 'MyFunc' to the type 'unsafe.Pointer' } type MyFunc func(a int, b int) (sum int) func SumInt(a, b int) int { return a + b } func test(x uintptr) { var xf MyFunc xf = MyFunc(x) // Cannot convert an expression of the type 'uintptr' to the type 'MyFunc' xf = MyFunc(unsafe.Pointer(x)) // Cannot convert an expression of the type 'unsafe.Pointer' to the type 'MyFunc' fmt.Println(xf(1, 2)) }
I searched on the internet but this information cannot be seen directly in google.
Thanks.
I found a solution! I need to pass a function pointer.
package main import ( "fmt" "unsafe" ) func main() { var f myfunc = sumint fmt.println(f(1, 2)) test(uintptr(unsafe.pointer(&f))) } type myfunc func(a int, b int) (sum int) func sumint(a, b int) int { return a + b } func test(x uintptr) { var xfp *myfunc xfp = (*myfunc)(unsafe.pointer(x)) var xf myfunc xf = *xfp fmt.println(xf(1, 2)) }
3 3 Process finished with the exit code 0
The above is the detailed content of What is the correct way to convert Go func to uintptr?. For more information, please follow other related articles on the PHP Chinese website!