I want to write a hook function that is called whenever a function is called in my program to gather some statistics about the arguments of the function. For example:
void hook(function f, ...){
//some statistics here
f(...);
}
int main(){
foo(1, 2);
}
So instead of calling foo
directly, it will call hook instead with foo
as its first argument and 1, 2
as extra arguments.
Is there anything similar to this in C? Can I achieve this goal in C in any other way?
Macros can be (ab)used to achieve this in a simplistic way:
void foo( int , int );
void Hook( int a , int b )
{
//do whatever
foo( a , b );
}
#define foo( a , b ) Hook( a , b )
int main( void )
{
foo( 1 , 2 );
}
Note that this is error prone and requires careful writing.
Perhaps this is what you are looking for?
typedef enum FunctionPointerType_E
{
FPT_Int_IntInt = 1
} FunctionPointerTypes_T
int foo(
int a,
int b
)
{
return(a+b);
}
void hook(
FunctionPointerTypes_T fpt,
void (*function)(void),
...
)
{
int rCode;
int (*fp_Int_IntInt)(int, int);
switch(fpt)
{
case FPT_Int_IntInt:
fp_Int_IntInt = (int(*)(int, int))function;
rCode=(*fp_Int_IntInt)(1,2);
...
}
return;
}
void CallFooByRefrence(void)
{
hook(FPT_Int_IntInt, (void(*)(void))foo, ...);
return;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.