Classes in D with betterC

user1234 user1234 at 12.de
Mon May 2 01:03:59 UTC 2022


On Sunday, 1 May 2022 at 19:51:19 UTC, Test123 wrote:
> Is there any example how to use betterC with LLVM Style RTTI ?

The basic blocks:

- you need an allocator that places RTTI after the instances
- you need an helper func that retrieve the RTTI

```d
#!dmd -betterC
module runnable;

import core.stdc.stdlib, core.stdc.stdio;

struct RTTI
{
   immutable uint  nameLen;
   immutable char* name;
   immutable uint  size;
   // etc...
}

struct RTTIAllocator
{
   static T** make(T,A...)(A a)
   {
     // one per type...
     __gshared RTTI rtti =
         RTTI(T.stringof.length, T.stringof.ptr, 
cast(uint)T.sizeof);

     void*[2]* r = cast(void*[2]*) malloc(size_t.sizeof * 2);
     (*r)[0] = malloc(T.sizeof);
     (*r)[1] = &rtti;

     auto result = cast(T**) r;
     (*result).__ctor(a);
     return result;
   }
}

const(RTTI)* getTypeInfo(void** instance)
{
   void*[2]* r = cast(void*[2]*) instance;
   return cast(RTTI*) (*r)[1];
}

struct Test
{
   int a;
   this(int a)
   {
     this.a = a;
   }
}

extern(C) void main()
{
   auto t = RTTIAllocator.make!Test(123);
   auto r = getTypeInfo(cast(void**)t);
   printf("`%s` has a size of `%d` byte\n", r.name, r.size);
}
```

The RTTI struct can contain everything that can be retrieved at 
compile time. Typically function addresses suc as the ctor, the 
dtor, vtable entries.

One must take care to the RTTI layout however. For example static 
arrays must not be stored, but rather just a pointer to first 
element plus its length, just like in the example.

And best of the lucks to make that `@safe`


More information about the Digitalmars-d-announce mailing list