Marshal.SizeOf Method (Object)
Assembly: mscorlib (in mscorlib.dll)
'Declaration <ComVisibleAttribute(True)> _ Public Shared Function SizeOf ( _ structure As Object _ ) As Integer 'Usage Dim structure As Object Dim returnValue As Integer returnValue = Marshal.SizeOf(structure)
The object whose size is to be returned.
Return ValueThe size of the structure parameter in unmanaged code.
The structure parameter is a null reference (Nothing in Visual Basic).
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.
This method uses SecurityAction.LinkDemand to prevent it from being called from untrusted code; only the immediate caller is required to have SecurityPermissionAttribute.UnmanagedCode permission. If your code can be called from partially trusted code, do not pass user input to Marshal class methods without validation. For important limitations on using the LinkDemand member, see Demand vs. LinkDemand.
The following code example creates a managed structure, transfers it to unmanaged memory, and then transfers it back to managed memory. This example uses the SizeOf method 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
Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.