challenge メソッドのフック

例えば、あるクラスのあるメソッドを実行する前に他の処理を呼びたい(例えばログやトランザクション開始など)。 また、そのメソッドの終了後にも何らかの後処理を呼びたい(トランザクション終了など)。

そのような、メソッドに対するフック処理を書いてください。 ライブラリを使用してメソッドのフックを実現した場合は ライブラリの名前を紹介してくれると助かります。

Posted feedbacks - D

RTTIの仮想関数テーブルを書き換えてみます。
D言語では明示的にfinalと指定しない限り、外から見えるメソッドはすべて仮想関数ですが、最適化によってインライン化された場合はダメかもしれません。
Testクラスのvtblを書き換えるだけなので、継承すると元に戻ります。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
private import std.stdio: writeln;

class Test {
    void print() {
        writeln("CTest.print");
    }
}

static class Test_hook {
    private static void* old_print;
    
    static this() {
        old_print = cast(void*)&Test.print;
        
        foreach(ref fp; Test.classinfo.vtbl) {
            if(fp == old_print) {
                fp = cast(void*)&typeof(this).print;
            }
        }
    }
    
    private void print() {
        writeln("CTest_hook.print before");
        (cast(void function(void*))old_print)(cast(void*)this);
        writeln("CTest_hook.print after");
    }
    
}

void main() {
    auto o = new Test();
    o.print;
}

Index

Feed

Other

Link

Pathtraq

loading...