Storing interfaces as void[]

David Zhang straivers98 at gmail.com
Fri Mar 12 17:57:06 UTC 2021


On Friday, 12 March 2021 at 17:46:22 UTC, Imperatorn wrote:
> On Friday, 12 March 2021 at 17:37:43 UTC, David  Zhang wrote:
>> I want to store interfaces as untyped void[], then cast them 
>> back to the interface at a later time. However, it appears to 
>> produce garbage values on get().
>>
>> Is this even possible, and if so, what is happening here? The 
>> alternative would be a struct { CheckedPtr self; api_fns.... }
>>
>> e.g.
>>
>> void register(I)(I i) {
>>   auto mem = new void[](I.sizeof);
>>   memcpy(mem.ptr, cast(void*) i, I.sizeof);
>>
>>   // CheckedPtr includes a hash of fullyQualifiedName
>>   map[i.get_name()] = CheckedPtr!I(mem.ptr);
>> }
>>
>> I get(I)() {
>>   // basically cast(I) p
>>   return map[I.get_name()].as!I();
>> }
>
> Have you tried using Variant or jsvar 
> (https://code.dlang.org/packages/arsd-official%3Ajsvar)? 🤔

It doesn't appear to support interfaces, see opAssign at line 682.

It occurs to me that I.sizeof == 8 which is just enough for the 
vtbl, but not enough for an implementation ptr. Maybe it's a 
pointer to a {self, vtbl} pair? SomeClass.sizeof == 16, which is 
enough storage for both...


More information about the Digitalmars-d-learn mailing list