• Advertisement
Sign in to follow this  

Just for curious

This topic is 4433 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

void bar () { // some code } void *pointer = bar; pointer(); 1. how to cast pointer to function type so that can call pointer() this way. 2.Can I directly do function call this way below: 1 void *pointer = some binary code; 2 cast pointer to function pointer type 3 call it :pointer ()

Share this post


Link to post
Share on other sites
Advertisement
You will need to look into Function Pointers.

void bar( /* args types go here w/ names as a reg function*/)
{
// some code
}

// Create a name for the function pointer
typedef void (*funcPtr)( /* args types go here */);

// Assign the function pointer
funcPtr yourPtr = &bar;

// Call the function pointer
(*yourPtr)(/* actual args go here */);

Share this post


Link to post
Share on other sites
Quote:
Original post by luasitdown
2.Can I directly do function call this way below:
  1. void *pointer = some binary code;
  2. cast pointer to function pointer type
  3. call it :pointer ()

Although generally in C++ polymorphism is superior to function pointers which in turn are superior to what you suggest, directly writing a function in binary and calling it is possible in C++, albeit not necessarily portable (the binary code will not be portable and some operating systems may not allow you to execute data as if it were code). Here is an example of how to do it (32-bit x86 code):
#include <iostream>

int main()
{
unsigned char buffer[] = {0xb8, 0x07, 0x00, 0x00, 0x00, 0xc3};
unsigned char * address = &buffer[0];
std::cout << (*reinterpret_cast< int (**)() >(&address))() << '\n';
}

The binary code {0xb8, 0x07, 0x00, 0x00, 0x00, 0xc3} breaks down as follows in intel x86 assembler:
0xb8, 0x07, 0x00, 0x00, 0x00: mov eax, 7
0xc3: ret
And is therefore equivalent to the simple function:
int function()
{
return 7;
}

This sequence of bytes is then cast to a pointer-to-pointer-to-function. Standard C++ disallows a direct pointer-to-object to pointer-to-function cast, which is why an extra level of indirection is required. The pointer-to-pointer-to-function is then dereferenced to yield a pointer-to-function (standard function pointer) and then invoked.

Enigma

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement