Z&#225&#59;by

Hi!

My problem is, when I use Marshal.SizeOf(typeof(MapData))

I only get the size of some element (wich is not in the struct constructor). Any ide how to get the real size of struct

Here is the code:

Code Snippet

public struct MapData

{

public MapData(int id)

{

mFields = new byte[1472];

mCol = new CollosionField[1472];

mName = new string[32];

mArea = id;

mXPos = new int();

mYPos = new int();

}

public string[] mName;

public int mArea;

public int mXPos;

public int mYPos;

public byte[] mFields;

public CollosionField[] mCol;

}

_size = Marshal.SizeOf(typeof(MapData));



Re: Visual C# Language Problem with Marshal.SizeOf()

Peter Ritchie

Managed objects do not have a specific size while they are managed. Why do you want to know the how much memory is used by an instance of that class




Re: Visual C# Language Problem with Marshal.SizeOf()

Záby

I want to store this structure in a binary file.

Code Snippet

fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None);

if (fs == null)

throw new Exception("Fajl m velet nem sikerult.");

byte[] buff = loadedMap.ToByteArray();

fs.Write(buff, 0, buff.Length);

fs.Close();

public byte[] ToByteArray()

{

byte[] buff = new byte[TSSize.Size];

GCHandle handle = GCHandle.Alloc(buff, GCHandleType.Pinned);

Marshal.StructureToPtr(this, handle.AddrOfPinnedObject(), false);

handle.Free();

return buff;

}

internal sealed class TSSize

{

public static int _size;

private static MapData tempMap = new MapData(1);

static TSSize()

{

_size = Marshal.SizeOf(typeof(MapData));

}

public static int Size

{

get

{

return _size;

}

}

}





Re: Visual C# Language Problem with Marshal.SizeOf()

Peter Ritchie

What you're storing is a bunch of memory pointers which will be useless once the object is out of memory (let alone when the application exits). I suggest you use the BinaryFormatter to serialize to a file. For example:

Code Snippet

using (FileStream fs = new FileStream("DataFile.dat", FileMode.Create))

{

// Construct a BinaryFormatter and use it to serialize the data to the stream.

BinaryFormatter formatter = new BinaryFormatter();

try

{

formatter.Serialize(fs, myObject);

}

catch (SerializationException e)

{

Console.WriteLine("Failed to serialize. Reason: " + e.Message);

throw;

}

}






Re: Visual C# Language Problem with Marshal.SizeOf()

Záby

It's working. Thank you for your help!