Search code examples
c++function-pointers

Incompatible pointer types assigning to 'int (*)(int, int, int, int, int)' from 'int *'


I have this pointer to an orgFunction takes 5 int as input and returns int, and orgfunctionhook takes the same args and return:

int (*orgFunction)(int a1, int a2 , int a3 , int a4, int a5);

int orgFunctionHook(int a1, int a2 , int a3 , int a4, int a5)
{
  // do something..
  return orgFunction(a1,a2,a3,a4,a5);
}

void Load(){
    orgFunction = (int*)HookFunction((char*)"something", 0x50000, (void*)orgFunctionHook);
}

And the HookFunction takes 3 args, const char, an address for my original function, and some hook

for ease this is the definition for it:

void* HookFunction(char* path, uint64_t vaddr, void* replace);

it returns a void*, my function i want to use it return int, once i use it in the Load()

I get this error:

" Incompatible pointer types assigning to 'int (*)(int, int, int, int, int)' from 'int *' "

My attempt to solve it was to declare it like this:

void Load(){
    void * orgFunction = (int*)HookFunction((char*)"something", 0x50000, (void*)orgFunctionHook);
}

but this makes a problem in the run time it when it runs the orgFunctionHook, the pointer address to the function orgFunction will be assinged as 0x0 ( EMPTY )

Is there could be another solution to pass this without losing the pointer to the origin function?

EDIT: Forgot to mention, that I can't change anything related to the HookFunction, its return or paramters remain the same.


Solution

  • You're casting to the wrong type. As mentioned in the error message, the function pointer has type int (*)(int,int,int,int,int) but you're attempting to assign an expression of type int * to it. These types are incompatible.

    The proper way to do this would be to create a typedef for the function pointer type:

    typedef int (*ftype)(int, int, int, int, int);
    

    Then you declare your function pointer with this type:

    ftype orgFunction;
    

    And similarly with HookFunction:

    ftype HookFunction(char* path, uint64_t vaddr, ftype replace);
    

    Then your Load function would look like this:

    void Load(){
        orgFunction = HookFunction((char*)"something", 0x50000, orgFunctionHook);
    }
    

    If you can't modify HookFunction, then just use the typedef in the call:

    void Load(){
        orgFunction = (ftype)HookFunction((char*)"something", 0x50000, (void *)orgFunctionHook);
    }