C++ Logo

std-proposals

Advanced search

Re: [std-proposals] A drift for c++ decorators;

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Sun, 27 Oct 2024 22:41:26 +0000
On Sat, Oct 26, 2024 at 6:25 PM zys wrote:
>
> When I want to execute additional code before functions
> without changing the source code, there are several
> approaches I can take.


I've been mulling over this idea for a while -- the idea of
intercepting a function call.

Let's say we have a class called 'MyClass', and all of its methods are virtual:

    class MyClass {
    public:
        virtual ~MyClass() = default;
        virtual char const *Hello(void) { return "Hello"; }
        virtual char const *Bye (void) { return "Bye"; }
    };

Next let's say we have a variable called 'obj' of type 'MyClass', and
we want to tweak this object so that every invocation of any of its
methods gets intercepted (we want to lock a mutex before the call, and
unlock the mutex after the call). Well. . . here's what you could do:
(1) Copy the MyClass VTable
(2) Edit the copied VTable so that each function pointer is replaced
with a pointer to an interceptor
(3) Write the machine code for each interceptor into a buffer of
executable memory
(4) Change the VTable pointer inside the object 'obj'

I spent a while on this up on GodBolt, and I have it working for both
GNU and Microsoft:

    https://godbolt.org/z/veqbhzhYq

Also not too long ago I started a draft paper on Interceptor Functions:

    http://www.virjacode.com/papers/interceptor.htm

But of course I realise that what you're proposing, zys, is that C++
would have a neat convenient way of doing this.

Received on 2024-10-27 22:41:35