开发者

How to determine the size of an instance?

开发者 https://www.devze.com 2023-04-10 01:31 出处:网络
I have set my project to accept unsafe code and have the following helper Class to determine the size of an instance:

I have set my project to accept unsafe code and have the following helper Class to determine the size of an instance:

struct MyStruct
    {
        public long a;
        public long b;
    }

public static class CloneHelper
    {
        public unsafe static void GetSize(BookSetViewModel book)
        {
            long n = 0;

            MyStruct inst;
            inst.a = 0;
            inst.开发者_如何学JAVAb = 0;
            n = Marshal.SizeOf(inst);
        }
}

This works perfectly fine with a struct. However as soon as I use the actual class-instance that is passed in:

public unsafe static void GetSize(BookSetViewModel book)
        {
            long n = 0;


            n = Marshal.SizeOf(book);
        }

I get this error:

Type 'BookSetViewModel' cannot be marshaled as an unmanaged structure; no meaningful size or offset can be computed.

Any idea how I could fix this? Thanks,


Well, it really depends on what you mean by the "size" of an instance. There's the size of the single object in memory, but you usually need to think about any objects that the root object refers to. That's how much memory may be reclaimable after the root becomes eligible for garbage collection... but you can't just add them up, as those objects may be referred to by multiple other objects, and indeed there may be repeated references even within a single object.

This blog post shows some code I've used before to determine the size of the raw objects (header + fields), disregarding any extra cost due to the objects that one object refers to. It's not something I would use in production code, but it's useful for experimenting with how large an object is under varying circumstances.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号