www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Finding the allocated size of a class?

reply Christopher Wright <dhasenan gmail.com> writes:
Hey --

I'm trying to find how much space on the heap an object will take up. I'm
basically trying to bypass constructors -- I have to create objects
successfully, even if their constructors are:
this () { throw new Exception(); }

So, my strategy is to allocate enough space to hold the object and insert a
pointer to the class's vtbl in the first sizeof(size_t) bytes of the allocated
memory, then cast to the desired type. Which is pretty much what the 'new'
keyword does. And I can find the vtbl easily enough. What about the amount of
memory to allocate?

I can use Type.sizeof to get the size of the type on the stack.
I can use Type.classinfo.tsize() to get the size of the type on the stack.
I'm dealing with objects, so that's a constant -- it's (void*).sizeof.

Once I've allocated memory with the garbage collector, I can find the size of
it with std.gc.capacity. So, I can find the size of any object I can create
with a constructor:

T t = new T();
uint footprint = std.gc.capacity(*(cast(void**)(&t)));

I could go through T.classinfo.offTi:

auto capacity = std.gc.capacity(*(cast(void**)(&(new Object()))));
foreach (offti; T.classinfo.offTi) {
   capacity += offTi.ti.tsize();
}

Except offTi is empty, even if I add fields to the class.

Does anyone know how to get the allocated size of a class without instantiating
it?
Nov 10 2007
next sibling parent reply "Steven Schveighoffer" <schveiguy yahoo.com> writes:
"Christopher Wright" wrote
 Does anyone know how to get the allocated size of a class without 
 instantiating it?
if you are using D2.0, this should work I think: size_t classSize = __traits(classInstanceSize, MyClass); If using D 1.0, not sure :) -Steve
Nov 10 2007
parent Christopher Wright <dhasenan gmail.com> writes:
Steven Schveighoffer Wrote:

 
 "Christopher Wright" wrote
 Does anyone know how to get the allocated size of a class without 
 instantiating it?
if you are using D2.0, this should work I think: size_t classSize = __traits(classInstanceSize, MyClass); If using D 1.0, not sure :)
D'oh! Should've thought of that. Thanks!
 -Steve 
 
 
Nov 10 2007
prev sibling parent Christian Kamm <kamm.incasoftware shift-at-left-and-remove-this.de> writes:
 Does anyone know how to get the allocated size of a class without
 instantiating it?
The comments page on classes suggests: obj.classinfo.init.length or Class.classinfo.init.length I didn't try it though. Christian
Nov 11 2007