Implementation

Interfaces have the following binary layout:[1]

struct IBar {
    typedef void (*funtion)();
    void*      pv;     // pointer to bound object
    funtion*   table;  // pointer into function table
};

When an interface instance is bound to an object, the pointer pv points to the bound object and the pointer table points into an array of function pointers with static storage duration. The array contains a function pointer for each member function of the interface; the signature of a function in the array is the same as the signature of the corresponding interface member function except that it has an additional leading parameter of type void*.

The function corresponding to an interface member function with the signature result f(arg1, ..., argn) is implemented roughly as follows, where T is the static type of the object at the point it was bound to the interface instance:

void f_impl(void* pv, arg1 a1, ..., argn an)
{
    static_cast<T*>(pv)->f(a1, ..., an);
}

The invocation of an interface member function:

int main()
{
    IBar b = ...;
    b.foo(a1, ..., an);
}

can be represented roughly as follows, where offset is a compile-time constant:

int main()
{
    IBar b = ...;
    (*b.table[offset])(b.pv, a1, ..., an);
}

[1]Assuming the Empty Base Optimization (EBO) is applied. This optimization is not required by the standard, but is required for the current implementation to work. Two implementations which did not depend on the EBO for correctness were considered, but both had shortcomings in areas other than standard conformance.


Sha'arei Tefila, an Orthodox Shul (Synagogue) in Salt Lake City, Utah Chabad Lubavitch of Utah