【问题标题】:Correct casting to function pointer that points to a function that returns a function正确转换为指向返回函数的函数的函数指针
【发布时间】:2017-04-28 01:05:04
【问题描述】:

我正在反转一个源代码,我发现了一个看起来像这样的函数:

考虑一下:

int examplefn(int x) { return x * 4; }

int (*rtx())(int)
{
    return examplefn;
}

好吧,然后我需要一个指向rtx() 的指针函数来做一个钩子,然后 我做过这样的事情:

int (*fncptr())(int) = (int(*())(int))0xC0FFEE; 
/* 0xC0FFEE it's a sample of the memory address of the function...*/

但是我的编译器没有编译,然后我尝试做:

typedef int(*fnc_t())(int);

// Clearer example pointing to rtx

fnc_t* TRY_2 = (fnc_t*)&rtx;

// then has successfully compiled, ex test...

 int main()
 {
    std::cout << TRY_2()(4) << std::endl; // output: 16 ok.
 }

好吧,我要直截了当,¿如何在不使用 typedef 的情况下进行正确的转换?

我在互联网上搜索了所有东西,但我没有找到任何东西......

【问题讨论】:

    标签: c++ visual-c++ c++14 function-pointers


    【解决方案1】:

    为什么要避免使用 typedef?它使代码更容易理解:

    using F = int(*)(int); // pointer to function taking int and returning int
    using G = F(*)();      // pointer to function taking nothing and returning
                           //   a pointer to function taking int and returning int
    

    这让我没有时间写作,其他人也没有时间阅读和理解。我称之为胜利。

    【讨论】:

      【解决方案2】:

      (int(*())(int)) 是一个函数类型(与函数rtx 的类型相同)。您的代码尝试声明一个函数,并将一个整数转换为函数。然而,你实际上想要处理一个 指向这样一个函数的指针。

      在:typedef int(*fnc_t())(int); 之后,可以通过在 typedef:int (*(*x)())(int) 中将 fnc_t 替换为 (*x) 来找到 fnc_t *x; 的等价物。所以你的代码可能是:

      int (*(*fncptr)())(int) = (int(*(*)())(int))0xC0FFEE; 
      

      在实际代码中使用一系列typedefs(或等效的usings)当然更可取。

      【讨论】:

        猜你喜欢
        • 2011-01-12
        • 2020-04-29
        • 2013-04-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-03
        • 1970-01-01
        • 2017-05-22
        相关资源
        最近更新 更多