Go: convert unsafe.Pointer to function pointer and vice versa

荒凉一梦 提交于 2019-12-06 00:07:18

As Jsor's answer shows, you can do this. Beware that you can do bad things:

package main

import (
    "fmt"
    "unsafe"
)

func main() {
    f1 := func(s string) {}
    f2 := func(i int) int { return i + 1 }
    pointers := []unsafe.Pointer{
        unsafe.Pointer(&f1),
        unsafe.Pointer(&f2),
    }
    f3 := (*func(int) bool)(pointers[1]) // note, not int
    fmt.Println((*f3)(1))
}

playground

It appears to work:

package main

import (
    "fmt"
    "unsafe"

    "math"
)

func main() {
    fn := print
    faked := *(*func(float64))(unsafe.Pointer(&fn))
    faked(1.0)

    // For comparison
    num := math.Float64bits(1.0)
    print(num)
}

func print(a uint64) {
    fmt.Println(a)
}

Will print

4607182418800017408

4607182418800017408

Of course, you're probably well aware of the potential problems with trying this.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!