Go:将unsafe.Pointer转换为函数指针,反之亦然 [英] Go: convert unsafe.Pointer to function pointer and vice versa

查看:787
本文介绍了Go:将unsafe.Pointer转换为函数指针,反之亦然的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C语言中,你可以把函数指针放入一个void指针数组中,并将它们转换回任何类型的函数指针:

  extern int(* fn1)(void); 
extern void(* fn2)(int);
void foo(void)
{
void * array [2];
int i;

/ *从函数指针到void指针的隐式转换* /
array [0] = fn1;
array [1] = fn2;
for(i = 0; i <2; i ++)
{
int(* fp)(int,int,int);

/ *从void指针到函数指针的隐式转换* /
fp = array [i];
/ *具有不同签名的呼叫功能* /
fp(1,2,3);


$ / code>

我需要在Go中执行相同的操作,使用不安全.Pointers。问题是:


  • Go函数指针可以转换为unsafe.Pointer吗?

  • 可以将不安全的指针转换为与原始函数指针不同(或相同)类型的Go函数指针吗?


(问题是 not 为什么或者我是否需要这样做;在给定的情况下,调用具有错误参数集的函数并错误解释返回值是可以的,因为调用者和被调用者)

解决方案

它似乎工作:

 主包

导入(
fmt
不安全

数学


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

//比较
num:= math.Float64bits(1.0)
print(num)
}

func print(a uint64){
fmt.Pr intln(a)
}

将打印


4607182418800017408

4607182418800017408



<当然,你可能很清楚这种尝试的潜在问题。


In C you can put function pointers into an array of void pointers and convert them back to function pointers of any type:

extern int (*fn1)(void);
extern void (*fn2)(int);
void foo(void)
{
        void *array[2];
        int i;

        /* implicit cast from function pointer to void pointer */
        array[0] = fn1;
        array[1] = fn2;
        for (i = 0; i < 2; i++)
        {
                int (*fp)(int, int, int);

                /* implicit cast from void pointer to function pointer */
                fp = array[i];
                /* call function with a different signature */
                fp(1, 2, 3);
        }
}

I need to do the same in Go, using unsafe.Pointers. The questions are:

  • Can a Go function pointer be converted to an unsafe.Pointer?
  • Can an unsafe.Pointer be converted to a Go function pointer of a different (or the same) type as the original function pointer?

(The question is not why or whether I need to do that; in the given situation it is okay to call a function with the wrong set of parameters and to misinterpret the return value because the caller and the callees are able to deal with that.)

解决方案

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.

这篇关于Go:将unsafe.Pointer转换为函数指针,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆