Set a function pointer to a static address

我们两清 提交于 2019-12-22 10:48:23

问题


I'm injecting a DLL into another process and want to call a function that is in that binary based on it's address (0x54315).

How can I actually declare a function, and then set it to this address?

#define FUNC 0x54315

void *myFuncPtr;

int main()
{
 myFuncPtr = FUNC;  // pretty sure this isn't how

 myFuncPtr(); // call it?
}

回答1:


The existing answers work, but you don't even need a variable for the function pointer. You can just do:

#define myfunc ((void (*)(void))0x54315)

and then call it as myfunc() just like you would an ordinary function. Note that you should change the type in the cast to match the actual argument and return types of the function.




回答2:


You need to define myFuncPtr as a function pointer, a void* isn't callable.

Best to use a typedef for that:

typedef void (*funptr)(void);
funprt myFuncPtr;

(Assuming your function takes nothing and returns nothing.)

Then you'll get a warning on the assignment - use a type cast to "silence" it, since this is indeed what you need to do.

You're pretty much on your own with this though, if the signature doesn't match, the calling convention is wrong, or the address is wrong, the compiler cannot validate anything and you get to pick up the pieces.




回答3:


Your code should work once the syntax is corrected to actually be a function pointer. I failed to read it properly for my first version of this answer. Sorry.

As stated by Mat, the proper syntax for a function pointer would be:

void (*myFuncPtr)(void) = (void (*)(void)) FUNC;

This is often simplified by using a typedef since the C function pointer syntax is somewhat convoluted.

Also, you're must be really sure the function to be called is at that same exact address every time your injected DLL runs. I'm not sure how you can be sure of that, though ...

Also, you would need to pay attention to the calling conventions and any arguments the function at FUNC might be expecting, since if you get that wrong you will likely end up with stack corruption.



来源:https://stackoverflow.com/questions/10673848/set-a-function-pointer-to-a-static-address

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!