nik*_*ter 1 c++ function-pointers visual-c++ c++14
我正在翻转源代码,我发现了一个看起来像这样的函数:
考虑一下:
int examplefn(int x) { return x * 4; }
int (*rtx())(int)
{
return examplefn;
}
Run Code Online (Sandbox Code Playgroud)
那么,我需要做一个指针函数rtx()来做一个钩子,然后我做了这样的事情:
int (*fncptr())(int) = (int(*())(int))0xC0FFEE;
/* 0xC0FFEE it's a sample of the memory address of the function...*/
Run Code Online (Sandbox Code Playgroud)
但我的编译器没有编译它,然后我尝试过:
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.
}
Run Code Online (Sandbox Code Playgroud)
好吧,我要说明一点,¿我怎样才能在不使用的情况下进行正确的铸造typedef?
我搜索了整个互联网,我没有找到任何东西......
为什么要避免使用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
Run Code Online (Sandbox Code Playgroud)
这让我没有时间写作,其他人没有时间阅读和理解.我称之为胜利.
(int(*())(int))是一个函数类型(与函数类型相同rtx).您的代码尝试声明一个函数,并将一个整数转换为函数.但是你实际上想要处理指向这样一个函数的指针.
后:typedef int(*fnc_t())(int);,相当于fnc_t *x;可以通过替换找到fnc_t与(*x)在的typedef: int (*(*x)())(int).所以你的代码可能是:
int (*(*fncptr)())(int) = (int(*(*)())(int))0xC0FFEE;
Run Code Online (Sandbox Code Playgroud)
在实际代码中使用一系列typedefs(或等价的usings)当然是优选的.
| 归档时间: |
|
| 查看次数: |
69 次 |
| 最近记录: |