Search code examples
c++visual-c++vtable

Detect the the vtable offset of a specific virtual function (using Visual C++)


Can the vtable offset of a specific virtual function be inspected?

Why? I'd like to be able to detect unintentional binary compatibility breaks (see http://techbase.kde.org/Policies/Binary_Compatibility_Issues_With_C%2B%2B for what I mean by binary compatibility).

I'm aware of the undocumented and unsupported technique of "/d1reportSingleClassLayout" (http://blogs.msdn.com/b/vcblog/archive/2007/05/17/diagnosing-hidden-odr-violations-in-visual-c-and-fixing-lnk2022.aspx), and I plan to use this technique, but I'd like to also use some simple compile time or run time checks if possible.


Solution

  • Inspired by Jerry's answer, I managed to write up this function that can do the same thing for any function signature:

    #include <iostream>
    
    struct A
    {
        virtual void a() {}
        virtual void b() {}
        virtual void c() {}
    };
    
    template <class T>
    int SeeBits(T func)
    {
        union
        {
            T ptr;
            int i;
        };
        ptr = func;
    
        return i;
    }
    
    int main()
    {
        int i = SeeBits(&A::a);
        int j = SeeBits(&A::b);
        int k = SeeBits(&A::c);
    
        std::cout << i << " " << j << " " << k << std::endl;
    
        return 0;
    }