我需要在 Go 代码中传递和接收 Go 函数。
由于系统调用在 Go 语言中的工作方式,因此用于“passage”的类型是
uintptr
。uintptr
,我别无选择,因为syscall.SyscallN
接受并返回这种类型。
将 Go
func
转换为 uintptr
的正确方法是什么?
我试过在沙盒中玩,但我不能简单地转换它。
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))
}
我在网上搜索过,但是这个信息在谷歌中是看不到的。
谢谢。