mardi 10 janvier 2023

How to intercept a method call?

Please refer to this question first:

How to ensure that every method of a class calls some other method first?

By overloading -> operator, we can call some function whenever -> is used. I was wondering if there is some way to figure out what function is being called as well?

Example:

struct foo{

void func1(){

}

void func2(){

}

}

struct Bar{

void someFunc(foo* f){
    f->func1();
}

}


struct Baz{

void someFunc(foo* f){
    f->func2();
}

}

In above example, Bar and Baz can call func1 and func2. One approach is that in every class we implement some code that calls a logging function informing it the method name being called.

The other approach is overloading the -> operator to call some log() function

struct LoggingFoo : private Foo {
    void log() const { }

    // Here comes the trick
    Foo const *operator -> () const { log(); return this; }
    Foo       *operator -> ()       { log(); return this; }
};

The only problem is how to pass some information to log(), so it knows what function is being called ?

EDIT:

Found this other approach:

https://www.codeproject.com/Articles/34237/A-C-Style-of-Intercepting-Functions

Aucun commentaire:

Enregistrer un commentaire