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

6rqinv9w  于 2024-01-09  发布在  其他
关注(0)|答案(2)|浏览(130)

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

  1. int examplefn(int x) { return x * 4; }
  2. int (*rtx())(int)
  3. {
  4. return examplefn;
  5. }

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

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


但我的编译器没有编译它,然后我试着做:

  1. typedef int(*fnc_t())(int);
  2. // Clearer example pointing to rtx
  3. fnc_t* TRY_2 = (fnc_t*)&rtx;
  4. // then has successfully compiled, ex test...
  5. int main()
  6. {
  7. std::cout << TRY_2()(4) << std::endl; // output: 16 ok.
  8. }


好吧,我说到重点了,我怎么能不使用typedef来做正确的转换呢?
我在互联网上找了一遍,什么都没找到。

rsaldnfx

rsaldnfx1#

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

  1. using F = int(*)(int); // pointer to function taking int and returning int
  2. using G = F(*)(); // pointer to function taking nothing and returning
  3. // 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;的等价物。因此您的代码可能是:

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

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

相关问题