Overwriting function pointer raises error: non-object type is not assignable

五迷三道 提交于 2020-06-28 05:05:39

问题


I'm currently working on a demo to monkey patch c function calls, the idea is that you have a shared c file (eg: lib.c), which has one exported function called void foo() in the header file lib.h.

Currently I'm trying to do the following:

#include <stdio.h>
#include "lib.h"

void (*foo_original)() = NULL;
void foo_patch()
{    
    puts("Before foo!");
    (*foo_original)();
    puts("Before foo!");
}

int main()
{
    foo_original = &foo;
    foo = &foo_patch;

    // Somewhere else in the code
    foo();
}

However this gives me the following error:

error: non-object type 'void ()' is not assignable

Does anyone know how I could fix this? Thanks


回答1:


This line:

foo = &foo_patch;

Is not reassigning the function pointer, but trying to reassign the address of the function foo itself, which is not permissible because that's an r-value.

If you were to reassign the pointer foo_original to point to foo_patch instead, you'd get an infinite recursion loop because foo_patch calls the function pointed to by foo_original.



来源:https://stackoverflow.com/questions/44618937/overwriting-function-pointer-raises-error-non-object-type-is-not-assignable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!