Set a function pointer to a static address

2020-07-23 05:13发布

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?
}

3条回答
老娘就宠你
2楼-- · 2020-07-23 05:18

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.

查看更多
forever°为你锁心
3楼-- · 2020-07-23 05:27

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.

查看更多
太酷不给撩
4楼-- · 2020-07-23 05:35

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.

查看更多
登录 后发表回答