Storing interfaces as void[]

David Zhang straivers98 at gmail.com
Sat Mar 13 00:36:37 UTC 2021


On Friday, 12 March 2021 at 22:18:59 UTC, tsbockman wrote:
> Why do you think you need a `void[]` slice? I think `void*` 
> pointers are sufficient. This handles all normal data types, as 
> long as they are allocated on the GC heap:

I wanted to have the registry own the structs' memory, though 
using new makes more sense on second thought. Your example 
templated implementation makes so much sense, though it doesn't 
work in this case. Thanks for the idea though.


>> Aye, I'm using hashes. The idea is to support either D 
>> interfaces or structs with arbitrary content.
>
> You can use TypeInfo references as the keys for the struct 
> types, too. It's better than hashes because the TypeInfo is 
> already being generated anyway, and is guaranteed to be unique, 
> unlike your hashes which could theoretically collide.

Makes sense. Using TypeInfo never occurred to me. I assume they 
are generated for COM classes as well?

>>> `I` is *not* the type of an interface instance, it is the 
>>> type of a reference to an instance of the interface.
>>
>> So `I i` is a reference to the instance, which itself holds a 
>> reference to the implementation, like a reference to a 
>> delegate (pointer to (ctx, fn))?
>
> No. What you are calling "the implementation" is the same thing 
> as "the instance". `I i` is a reference into the interior of 
> the implementing class instance, offset such that it points at 
> the virtual function table pointer for that interface. The 
> lowering is something like this:
>
> ////////////////////////////////
> interface I { ... }
> class C : I { ... }
> struct C_Instance {
>     void* __vtblForC;
>     // ... other junk
>     void* __vtblForI;
>     // ... explicit and inherited class fields, if any.
> }
>
> C c = new C; // Works like `C_Instance* c = new C_Instance;`
> I i = c; // Works like `void** i = 
> (C_Instance.__vtblForI.offsetof + cast(void*) c);`

Makes sense, I always thought of them as existing in separate 
places.

So much head-bashing, and it's over. Thanks, tsbockman, 
Imperatorn.



More information about the Digitalmars-d-learn mailing list