在Go语言中,将一个`func`类型转换为`uintptr`类型是一项常见的操作,但是正确的方法并不是直接进行转换,因为这样可能会导致一些潜在的问题。正确的方法是使用`unsafe`包中的`Pointer`函数,将`func`类型的值先转换为`unsafe.Pointer`类型,然后再将其转换为`uintptr`类型。这样可以确保类型转换的安全性,避免出现不可预料的错误。这种方法虽然需要使用`unsafe`包,但是在合适的情况下,可以有效地解决将`Go func`转换为`uintptr`的问题。
问题内容
我需要在 go 代码中传递和接收 go 函数。
由于 go 语言中系统调用的工作方式,用于“passage”的类型是
。
除了
之外我别无选择,因为
接受并返回此类型。
将 go
转换为
的正确方法是什么?
go语言参考手册 中文CHM版
Go 是一个开源的编程语言,它能让构造简单、可靠且高效的软件变得容易。本文给大家带来Go参考手册,需要的可以来下载! Go是从2007年末由Robert Griesemer, Rob Pike, Ken Thompson主持开发,后来还加入了Ian Lance Taylor, Russ Cox等人,并最终于2009年11月开源,在2012年早些时候发布了Go 1稳定版本。现在Go的开发已经是完全开放的,并且拥有一个活跃的社区。 Go 语言特色 简洁、快速、安全 并行、有趣、开源 内存管理、v数组安全、编译
下载
我尝试在沙箱中使用它,但我无法简单地转换它。
我在互联网上进行了搜索,但此信息无法直接在 google 中看到。
谢谢。
解决方法
我找到办法了!
我需要传递一个函数指针。
uintptruintptrsyscall.syscallnfuncuintptrpackage 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))
}
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
