How can I calculate (manually) the SizeOf string and also add a class to the size?

First part:

I have a string ...

string sTest = "This is my test string";

      

How can I (manually, without code) determine the SizeOf string? What should you get? How do you get this size?


Second part:

I have a class ...

[StructLayout(LayoutKind.Sequential)]
public class TestStruct
{
    public string Test;
}

      

I use it ...

TestStruct oTest = new TestStruct();
oTest.Test = "This is my test string";

      

Are there size differences from the first part to the second part?


Update:

The point is that this size is used to create the memory card file.

long lMapSize = System.Runtime.InteropServices.Marshal.SizeOf(oTest);
mmf = MemoryMappedFile.CreateOrOpen("testmap", lMapSize);

      

I just thought it was worth it. Currently lMapSize = 4. What is confusing ... of me! Thanks everyone!

+3


source to share


1 answer


string

is a reference type, so a field inside another class or structure variable or local variable will be a pointer - IntPtr

. The size of the pointer is 32 bits on a 32-bit computer and 64 for 64.
If you want to know the size of the string itself, you need to know what encoding you are going to use. Encoding.UTF8.GetByteCount("aaa")

will return the size "aaa"

in UTF8 encoding. But this will only return the size of the string, not the size of the .net object.
There doesn't seem to be an exact way to calculate the size of an object from code. If you want to know what's going on in your application, there are some memory profilers for that, just search for "C # Memory Profiler". I've only used the heap-shot mono profiler, so I can't recommend you which one is good.

Another way is to use WinDBG with sos.dll and sosex.dll. Here you can find an example of using sos.dll.




Update:
You can also serialize your object to a byte array. The serializer will add additional information such as the name and version of the assembly.
byte[] bytes;
using (MemoryStream stream = new MemoryStream())
{
    IFormatter formatter = new BinaryFormatter();
    formatter.Serialize(stream, myObject);
    bytes = stream.ToArray();
}

using (MemoryStream stream = new MemoryStream(bytes))
{
    IFormatter formatter = new BinaryFormatter();
    myObject = formatter.Deserialize(stream);
}

      

+2


source







All Articles