Reputation: 1861
The question I'm asking won't be used in production, it's pure curiosity
Let's say I have a function, and its prototype is:
int myFunc(int, char*);
Supposing I know the static memory address (which is, for example, 0xC0DE), I can do this:
int (__cdecl* myFuncPtr)(int, char*) = (int(__cdecl*)(int, char*)) 0xC0DE;
myFuncPtr(1, "something");
Now, can I somehow call that function in one line, without the defining it? Like this:
((int(__cdecl*)) 0xC0DE)(1, "something");
Upvotes: 7
Views: 439
Reputation:
Cast to a function pointer type instead of to int*
:
((int(__cdecl*)(int, char const*)) 0xC0DE)(1, "something")
Note that this still invokes undefined behaviour and must be avoided unless your implementation explicitly documents you may do so and you don’t care about portability. If you want to be safe, at least use inline assembly so that you can rely on guarantees made by the target architecture, rather than by the compiler.
Upvotes: 14
Reputation: 283694
In C, but not C++, you can omit the argument types:
((int(*)()) 0xC0DE)(1, "something");
Upvotes: 4