Invoking a function by address
I am trying to learn a few different methods of calling functions by address.
bool gl_draw_text(uint x, uint y, uint color, uint alpha, char *fmt);
This function is what I'm calling. The following, is how I'm currently calling it. (And it works fine.)
static void glDrawText(char* text, int x, int y)
{
DWORD func = 0x开发者_StackOverflow中文版10057970;
__asm
{
push text
push 255
push 14
push y
push x
call dword ptr [func]
}
}
The method I want to use is this one.
void Hack()
{
bool (draw*)(uint, uint, uint, uint, char*);
draw = 0x10057970;
(draw)(20, 20, 14, 255, "Text");
}
But, I don't know how to properly cast the address to the function to make it work\compile. ?
There is also a method that uses a virtual function, I'm curious about how that method works too. (I can also use MS Detours, to hook, then call the function like that, how does that method work behind the scenes, if you know.)
So to be clear, I'm just asking for various methods of accomplishing this task, but listed a few I'm curious about after reading about them, etc,.
You can always cast:
typedef bool (*funcptr)(uint, uint, uint, uint, char*);
funcptr draw = (funcptr)0x10057970;
or in C++:
funcptr draw = reinterpret_cast<funcptr>(0x10057970);
However, this is completely undefined behaviour.
Also, in general, there's nothing to stop the compiler moving the target function, or even eliminating it entirely if it doesn't see it being called explicitly.
This code compiles (see http://ideone.com/celq1):
typedef unsigned int uint ;
int main()
{
bool (*draw)(uint, uint, uint, uint, const char*);
draw = reinterpret_cast<bool (*)(uint, uint, uint, uint, const char*)>(0x10057970);
draw(20, 20, 14, 255, "Text");
}
But of course it doesn't run :-)
PS I changed char*
to const char*
to get rid of a compiler warning. It looks like const char*
is what you want here, but it's not essential to the idea.
Edited to add: In fact, even this compiles, if you want to impress your friends:
typedef unsigned int uint ;
int main()
{
reinterpret_cast<bool (*)(uint, uint, uint, uint, const char*)>(0x10057970)
(20, 20, 14, 255, "Text");
}
精彩评论