英文:
What is the proper way to convert Go func into an uintptr?
问题
我需要在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)) // 无法将类型为'MyFunc'的表达式转换为'tuintptr'类型
test(uintptr(unsafe.Pointer(f))) // 无法将类型为'MyFunc'的表达式转换为'tunsafe.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) // 无法将类型为'uintptr'的表达式转换为'MyFunc'类型
xf = MyFunc(unsafe.Pointer(x)) // 无法将类型为'unsafe.Pointer'的表达式转换为'MyFunc'类型
fmt.Println(xf(1, 2))
}
我在互联网上搜索过,但在Google上直接找不到这些信息。
谢谢。
英文:
I need to pass and receive a Go function from and into Go code.
The type used for "passage" is uintptr
due to how system calls work in Go language.
I have no other choice other than uintptr
, because syscall.SyscallN
accepts and returns this type.
What is the proper way to convert Go func
into an uintptr
?
I tried to play with it in a sandbox, but I can not convert it simply.
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 in internet, but this information is not visible in Google directly.
Thank you.
答案1
得分: 0
我找到了一种方法!
我需要传递一个函数指针。
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))
}
<pre>
3
3
进程以退出代码0结束
</pre>
英文:
I have found a way !
I need to pass a pointer to function.
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))
}
<pre>
3
3
Process finished with the exit code 0
</pre>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论