digitalmars.D.learn - Finding the allocated size of a class?
- Christopher Wright (17/17) Nov 10 2007 Hey --
- Steven Schveighoffer (5/7) Nov 10 2007 if you are using D2.0, this should work I think:
- Christopher Wright (3/16) Nov 10 2007 D'oh! Should've thought of that.
- Christian Kamm (6/8) Nov 11 2007 The comments page on classes suggests:
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
"Christopher Wright" wroteDoes 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
Steven Schveighoffer Wrote:"Christopher Wright" wroteD'oh! Should've thought of that. Thanks!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
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