Reputation: 378
I was reversing a source code and I've found a function it which looks like:
consider this:
int examplefn(int x) { return x * 4; }
int (*rtx())(int)
{
return examplefn;
}
well, Then I needed make a pointer function to rtx()
to do a hook, then I've done something like this:
int (*fncptr())(int) = (int(*())(int))0xC0FFEE;
/* 0xC0FFEE it's a sample of the memory address of the function...*/
But my compiler did not compile it, then I've tried do:
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.
}
well, I'm getting to the point, How can I do the correct casting without use a typedef
?
I searched all over the internet and I have not found anything...
Upvotes: 1
Views: 94
Reputation: 141648
(int(*())(int))
is a function type (the same type as the function rtx
has). Your code attempts to declare a function, and cast an integer to function. However you actually want to deal with a pointer to such a function.
After: typedef int(*fnc_t())(int);
, the equivalent of fnc_t *x;
can be found by replacing fnc_t
with (*x)
in the typedef: int (*(*x)())(int)
. So your code could be:
int (*(*fncptr)())(int) = (int(*(*)())(int))0xC0FFEE;
Using a series of typedef
s (or equivalent using
s) is certainly preferable in real code.
Upvotes: 5
Reputation: 304122
Why do you want to avoid using a typedef? It makes code so much easier to understand:
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
This took me no time to write and everybody else no time to read and understand. I'd call that a win.
Upvotes: 6