2

I have a function at a known memory address(for example: 0x11111111). The function returns an int, and takes a uint32_t pointer as its only argument.

How would I call this function using c++? I have seen a few examples of calling a function by its address, but I can't seem to find one that takes a pointer as its argument

EDIT:I seen that. Doesn't address how to call the function that takes a pointer as an argument

Andrew Cottrell
  • 3,312
  • 3
  • 26
  • 41
user1698144
  • 754
  • 4
  • 13
  • 36
  • Use function pointers. – Raindrop7 Oct 29 '17 at 22:01
  • I seen that. Doesn't address how to call the function that takes a pointer as an argument – user1698144 Oct 29 '17 at 22:02
  • 2
    I don't see how that makes a difference. Feel free to edit to explain how it does. – Baum mit Augen Oct 29 '17 at 22:05
  • It is not recommended to do that. Simply If you were the one who is responsible for allocating memory in low level (choosing the addresses...) then it is a good idea like in low level languages like assembly. – Raindrop7 Oct 29 '17 at 22:13
  • 1
    Why would it make any difference whether it takes a pointer as an argument? You call it the same way, but instead of no arguments, you pass it a pointer as an argument. – user253751 Oct 29 '17 at 23:00

1 Answers1

2

If you’re sure that there’s a function there, you could call it by casting the address to a function pointer of the appropriate type, then calling it. Here’s C code to do this:

typedef int (*FunctionType)(uint32_t*);

FunctionType function = (FunctionType)0x11111111;
function(arg);

This can easily be modified to support any number of function arguments and any return type you’d like. Just tweak the argument types list of the FunctionType typedef.

Or, in one line (gulp):

(((int (*)(uint32_t *)) 0x11111111)(arg);
M.M
  • 138,810
  • 21
  • 208
  • 365
templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065