c++ 正确转换为指向返回函数的函数的函数指针

6rqinv9w  于 9个月前  发布在  其他
关注(0)|答案(2)|浏览(89)

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

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来做正确的转换呢?
我在互联网上找了一遍,什么都没找到。

rsaldnfx

rsaldnfx1#

为什么要避免使用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

字符串
我没有花时间去写,其他人也没有时间去阅读和理解,我称之为胜利。

beq87vna

beq87vna2#

(int(*())(int))是一个函数类型(与rtx的函数类型相同)。您的代码试图声明一个函数,并将一个整数转换为函数。然而,您实际上想要处理一个指向 * 这样一个函数的 * 指针。
在:typedef int(*fnc_t())(int);之后,可以通过在typedef:int (*(*x)())(int)中将fnc_t替换为(*x)来找到fnc_t *x;的等价物。因此您的代码可能是:

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

字符串
在真实的代码中,使用一系列typedef s(或等效的using s)当然更可取。

相关问题