2

I am looking at injecting some code into a function and run that code just before a function returns. However, I do not want to include the code that I want to inject into that function as a header file etc.

Is there a way, to compile a file in a way such that we do not need to include the extra code as a header file and at the same time we can inject the extra code in a specefic function and run it before it terminates..

Just looking for ideas..

Thanks

user1479589
  • 315
  • 1
  • 4
  • 16
  • 1
    No, in fact I think you'll find it impossible to do this without modifying the functions themselvesa – daniel gratzer Feb 19 '14 at 16:56
  • Although the question I have proposed this as a duplicate of is for C++, the answer is essentially the same. Neither C nor C++ supports it overtly, but there are various things you can do either with the preprocessor or with the linker. – Eric Postpischil Feb 19 '14 at 16:59
  • 1
    Decidedly non-trivial at best; practically, very difficult. Is this a compile-time option? Does the injected code need to access local variables in the function, or is it free-standing? Your closest approach is likely to involve renaming the 'real' function, writing a hooking function with the name of the 'real' function that calls the renamed real function, does the hook operations, then returns the value. But that relies on not needing to access local variables. – Jonathan Leffler Feb 19 '14 at 17:00
  • I don't see how this is duplicate. – Heeryu Feb 20 '14 at 01:38

1 Answers1

0

Maybe a callback can do the job, something like:

typedef void (*fpointer)(void);

void foo(void){
    //fooing
}

void bar(void){
    //baring
}

void f(fpointer some_function){

    //do the joob

    //some other job before exiting
    some_function();
}

and use it as

f(foo);

or

f(bar);
Heeryu
  • 852
  • 10
  • 25