Marshal.SizeOf Method (Object)
Returns the unmanaged size of an object in bytes.
Assembly: mscorlib (in mscorlib.dll)
This method accepts an instance of a structure, which can be a reference type or a boxed value type. The layout must be sequential or explicit.
The size returned is the size of the unmanaged object. The unmanaged and managed sizes of an object can differ. For character types, the size is affected by the CharSet value applied to that class.
The following example creates a managed structure, transfers it to unmanaged memory, and then transfers it back to managed memory. This example uses themethod to determine how much unmanaged memory to allocate.
Imports System Imports System.Runtime.InteropServices Public Structure Point Public x As Integer Public y As Integer End Structure Module Example Sub Main() ' Create a point struct. Dim p As Point p.x = 1 p.y = 1 Console.WriteLine("The value of first point is " + p.x.ToString + " and " + p.y.ToString + ".") ' Initialize unmanged memory to hold the struct. Dim pnt As IntPtr = Marshal.AllocHGlobal(Marshal.SizeOf(p)) Try ' Copy the struct to unmanaged memory. Marshal.StructureToPtr(p, pnt, False) ' Create another point. Dim anotherP As Point ' Set this Point to the value of the ' Point in unmanaged memory. anotherP = CType(Marshal.PtrToStructure(pnt, GetType(Point)), Point) Console.WriteLine("The value of new point is " + anotherP.x.ToString + " and " + anotherP.y.ToString + ".") Finally ' Free the unmanaged memory. Marshal.FreeHGlobal(pnt) End Try End Sub End Module
Available since 8
Available since 1.1
Portable Class Library
Supported in: portable .NET platforms
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Available since 8.1