首頁  >  文章  >  後端開發  >  將 Go func 轉換為 uintptr 的正確方法是什麼?

將 Go func 轉換為 uintptr 的正確方法是什麼?

王林
王林轉載
2024-02-09 13:10:081121瀏覽

将 Go func 转换为 uintptr 的正确方法是什么?

在Go語言中,將一個`func`類型轉換為`uintptr`類型是一項常見的操作,但是正確的方法並不是直接進行轉換,因為這樣可能會導致一些潛在的問題。正確的方法是使用`unsafe`套件中的`Pointer`函數,將`func`類型的值先轉換為`unsafe.Pointer`類型,然後再轉換為`uintptr`類型。這樣可以確保類型轉換的安全性,避免出現不可預測的錯誤。這種方法雖然需要使用`unsafe`套件,但是在適當的情況下,可以有效地解決將`Go func`轉換為`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))                 // 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))
}

我在互聯網上進行了搜索,但此資訊無法直接在 google 中看到。

謝謝。

解決方法

我找到辦法了! 我需要傳遞一個函數指標。

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

以上是將 Go func 轉換為 uintptr 的正確方法是什麼?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除