Marshal Class
Important
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
Provides a collection of methods for allocating unmanaged memory, copying unmanaged memory blocks, and converting managed to unmanaged types, as well as other miscellaneous methods used when interacting with unmanaged code.
public ref class Marshal abstract sealed
public ref class Marshal sealed
public static class Marshal
public sealed class Marshal
type Marshal = class
Public Class Marshal
Public NotInheritable Class Marshal
- Inheritance
-
Marshal
The following example shows how to use various methods defined by the Marshal class.
using namespace System;
using namespace System::Runtime::InteropServices;
public value struct Point
{
public:
property int X;
property int Y;
};
extern bool CloseHandle(IntPtr h);
int main()
{
// Demonstrate the use of public static fields of the Marshal
// class.
Console::WriteLine(
"SystemDefaultCharSize={0},SystemMaxDBCSCharSize={1}",
Marshal::SystemDefaultCharSize,
Marshal::SystemMaxDBCSCharSize);
// Demonstrate the use of the SizeOf method of the Marshal
// class.
Console::WriteLine("Number of bytes needed by a Point object: {0}",
Marshal::SizeOf(Point::typeid));
Point point;
Console::WriteLine("Number of bytes needed by a Point object: {0}",
Marshal::SizeOf(point));
// Demonstrate how to call GlobalAlloc and
// GlobalFree using the Marshal class.
IntPtr hglobal = Marshal::AllocHGlobal(100);
Marshal::FreeHGlobal(hglobal);
// Demonstrate how to use the Marshal class to get the Win32
// error code when a Win32 method fails.
bool isCloseHandleSuccess = CloseHandle(IntPtr(-1));
if (!isCloseHandleSuccess)
{
Console::WriteLine(
"CloseHandle call failed with an error code of: {0}",
Marshal::GetLastWin32Error());
}
};
// This is a platform invoke prototype. SetLastError is true,
// which allows the GetLastWin32Error method of the Marshal class
// to work correctly.
[DllImport("Kernel32", ExactSpelling = true, SetLastError = true)]
extern bool CloseHandle(IntPtr h);
// This code produces the following output.
//
// SystemDefaultCharSize=2, SystemMaxDBCSCharSize=1
// Number of bytes needed by a Point object: 8
// Number of bytes needed by a Point object: 8
// CloseHandle call failed with an error code of: 6
using System;
using System.Text;
using System.Runtime.InteropServices;
public struct Point
{
public Int32 x, y;
}
public sealed class App
{
static void Main()
{
// Demonstrate the use of public static fields of the Marshal class.
Console.WriteLine("SystemDefaultCharSize={0}, SystemMaxDBCSCharSize={1}",
Marshal.SystemDefaultCharSize, Marshal.SystemMaxDBCSCharSize);
// Demonstrate the use of the SizeOf method of the Marshal class.
Console.WriteLine("Number of bytes needed by a Point object: {0}",
Marshal.SizeOf(typeof(Point)));
Point p = new Point();
Console.WriteLine("Number of bytes needed by a Point object: {0}",
Marshal.SizeOf(p));
// Demonstrate how to call GlobalAlloc and
// GlobalFree using the Marshal class.
IntPtr hglobal = Marshal.AllocHGlobal(100);
Marshal.FreeHGlobal(hglobal);
// Demonstrate how to use the Marshal class to get the Win32 error
// code when a Win32 method fails.
Boolean f = CloseHandle(new IntPtr(-1));
if (!f)
{
Console.WriteLine("CloseHandle call failed with an error code of: {0}",
Marshal.GetLastWin32Error());
}
}
// This is a platform invoke prototype. SetLastError is true, which allows
// the GetLastWin32Error method of the Marshal class to work correctly.
[DllImport("Kernel32", ExactSpelling = true, SetLastError = true)]
static extern Boolean CloseHandle(IntPtr h);
}
// This code produces the following output.
//
// SystemDefaultCharSize=2, SystemMaxDBCSCharSize=1
// Number of bytes needed by a Point object: 8
// Number of bytes needed by a Point object: 8
// CloseHandle call failed with an error code of: 6
Imports System.Text
Imports System.Runtime.InteropServices
Imports System.Security.Permissions
Public Structure Point
Public x, y As Int32
End Structure
Public NotInheritable Class App
<SecurityPermission(SecurityAction.LinkDemand, Unrestricted:=True)> _
Shared Sub Main()
' Demonstrate the use of public static fields of the Marshal class.
Console.WriteLine("SystemDefaultCharSize={0}, SystemMaxDBCSCharSize={1}", Marshal.SystemDefaultCharSize, Marshal.SystemMaxDBCSCharSize)
' Demonstrate the use of the SizeOf method of the Marshal class.
Console.WriteLine("Number of bytes needed by a Point object: {0}", Marshal.SizeOf(GetType(Point)))
Dim p As New Point()
Console.WriteLine("Number of bytes needed by a Point object: {0}", Marshal.SizeOf(p))
' Demonstrate how to call GlobalAlloc and
' GlobalFree using the Marshal class.
Dim hglobal As IntPtr = Marshal.AllocHGlobal(100)
Marshal.FreeHGlobal(hglobal)
' Demonstrate how to use the Marshal class to get the Win32 error
' code when a Win32 method fails.
Dim f As [Boolean] = CloseHandle(New IntPtr(-1))
If Not f Then
Console.WriteLine("CloseHandle call failed with an error code of: {0}", Marshal.GetLastWin32Error())
End If
End Sub
' This is a platform invoke prototype. SetLastError is true, which allows
' the GetLastWin32Error method of the Marshal class to work correctly.
<DllImport("Kernel32", ExactSpelling:=True, SetLastError:=True)> _
Shared Function CloseHandle(ByVal h As IntPtr) As [Boolean]
End Function
End Class
' This code produces the following output.
'
' SystemDefaultCharSize=2, SystemMaxDBCSCharSize=1
' Number of bytes needed by a Point object: 8
' Number of bytes needed by a Point object: 8
' CloseHandle call failed with an error code of: 6
The static
methods defined on the Marshal class are essential to working with unmanaged code. Most methods defined in this class are typically used by developers who want to provide a bridge between the managed and unmanaged programming models. For example, the StringToHGlobalAnsi method copies ANSI characters from a specified string (in the managed heap) to a buffer in the unmanaged heap. It also allocates the target heap of the right size.
The common language runtime provides specific marshaling capabilities. For details on marshaling behavior, see Interop Marshaling.
The Read
and Write
methods in the Marshal class support both aligned and unaligned access.
System |
Represents the default character size on the system; the default is 2 for Unicode systems and 1 for ANSI systems. This field is read-only. |
System |
Represents the maximum size of a double byte character set (DBCS) size, in bytes, for the current operating system. This field is read-only. |
Add |
Increments the reference count on the specified interface. |
Alloc |
Allocates a block of memory of specified size from the COM task memory allocator. |
Alloc |
Allocates memory from the unmanaged memory of the process by using the specified number of bytes. |
Alloc |
Allocates memory from the unmanaged memory of the process by using the pointer to the specified number of bytes. |
Are |
Indicates whether runtime callable wrappers (RCWs) from any context are available for cleanup. |
Bind |
Gets an interface pointer identified by the specified moniker. |
Change |
Changes the strength of an object's COM Callable Wrapper (CCW) handle. |
Cleanup |
Notifies the runtime to clean up all Runtime Callable Wrappers (RCWs) allocated in the current context. |
Copy(Byte[], Int32, Int |
Copies data from a one-dimensional, managed 8-bit unsigned integer array to an unmanaged memory pointer. |
Copy(Char[], Int32, Int |
Copies data from a one-dimensional, managed character array to an unmanaged memory pointer. |
Copy(Double[], Int32, Int |
Copies data from a one-dimensional, managed double-precision floating-point number array to an unmanaged memory pointer. |
Copy(Int16[], Int32, Int |
Copies data from a one-dimensional, managed 16-bit signed integer array to an unmanaged memory pointer. |
Copy(Int32[], Int32, Int |
Copies data from a one-dimensional, managed 32-bit signed integer array to an unmanaged memory pointer. |
Copy(Int64[], Int32, Int |
Copies data from a one-dimensional, managed 64-bit signed integer array to an unmanaged memory pointer. |
Copy(Int |
Copies data from an unmanaged memory pointer to a managed 8-bit unsigned integer array. |
Copy(Int |
Copies data from an unmanaged memory pointer to a managed character array. |
Copy(Int |
Copies data from an unmanaged memory pointer to a managed double-precision floating-point number array. |
Copy(Int |
Copies data from an unmanaged memory pointer to a managed 16-bit signed integer array. |
Copy(Int |
Copies data from an unmanaged memory pointer to a managed 32-bit signed integer array. |
Copy(Int |
Copies data from an unmanaged memory pointer to a managed 64-bit signed integer array. |
Copy(Int |
Copies data from an unmanaged memory pointer to a managed IntPtr array. |
Copy(Int |
Copies data from an unmanaged memory pointer to a managed single-precision floating-point number array. |
Copy(Int |
Copies data from a one-dimensional, managed IntPtr array to an unmanaged memory pointer. |
Copy(Single[], Int32, Int |
Copies data from a one-dimensional, managed single-precision floating-point number array to an unmanaged memory pointer. |
Create |
Obsolete.
Aggregates a managed object with the specified COM object. |
Create |
Aggregates a managed object of the specified type with the specified COM object. |
Create |
Obsolete.
Wraps the specified COM object in an object of the specified type. |
Create |
Wraps the specified COM object in an object of the specified type. |
Destroy |
Obsolete.
Frees all substructures that the specified unmanaged memory block points to. |
Destroy |
Frees all substructures of a specified type that the specified unmanaged memory block points to. |
Final |
Releases all references to a Runtime Callable Wrapper (RCW) by setting its reference count to 0. |
FreeBSTR(Int |
Frees a |
Free |
Frees a block of memory allocated by the unmanaged COM task memory allocator. |
Free |
Frees memory previously allocated from the unmanaged memory of the process. |
Generate |
Returns the globally unique identifier (GUID) for the specified type, or generates a GUID using the algorithm used by the Type Library Exporter (Tlbexp.exe). |
Generate |
Returns a programmatic identifier (ProgID) for the specified type. |
Get |
Obtains a running instance of the specified object from the running object table (ROT). |
Get |
Obsolete.
Returns a pointer to an IUnknown interface that represents the specified interface on the specified object. Custom query interface access is controlled by the specified customization mode. |
Get |
Obsolete.
Returns a pointer to an IUnknown interface that represents the specified interface on the specified object. Custom query interface access is enabled by default. |
Get |
Returns a pointer to an IUnknown interface that represents the specified interface on an object of the specified type. Custom query interface access is enabled by default. |
Get |
Returns an interface pointer that represents the specified interface for an object, if the caller is in the same context as that object. |
Get |
Retrieves data that is referenced by the specified key from the specified COM object. |
Get |
Retrieves the virtual function table (v-table or VTBL) slot for a specified MemberInfo type when that type is exposed to COM. |
Get |
Obsolete.
Converts an unmanaged function pointer to a delegate. |
Get |
Converts an unmanaged function pointer to a delegate of a specified type. |
Get |
Retrieves the last slot in the virtual function table (v-table or VTBL) of a type when exposed to COM. |
Get |
Obsolete.
Retrieves a code that identifies the type of the exception that occurred. |
Get |
Converts the specified HRESULT error code to a corresponding Exception object, with additional error information passed in an IErrorInfo interface for the exception object. |
Get |
Converts the specified HRESULT error code to a corresponding Exception object. |
Get |
Retrieves a computer-independent description of an exception, and information about the state that existed for the thread when the exception occurred. |
Get |
Obsolete.
Converts a delegate into a function pointer that is callable from unmanaged code. |
Get |
Converts a delegate of a specified type to a function pointer that is callable from unmanaged code. |
GetHINSTANCE(Module) |
Returns the instance handle (HINSTANCE) for the specified module. |
Get |
Converts the specified exception to an HRESULT. |
Get |
Returns the HRESULT corresponding to the last error incurred by Win32 code executed using Marshal. |
Get |
Returns an IDispatch interface from a managed object. |
Get |
Returns an IDispatch interface pointer from a managed object, if the caller is in the same context as that object. |
Get |
Returns a ITypeInfo interface from a managed type. |
Get |
Returns an IUnknown interface from a managed object. |
Get |
Returns an IUnknown interface from a managed object, if the caller is in the same context as that object. |
Get |
Get the last platform invoke error on the current thread. |
Get |
Gets the system error message for the last PInvoke error code. |
Get |
Gets the last system error on the current thread. |
Get |
Returns the error code returned by the last unmanaged function that was called using platform invoke that has the SetLastError flag set. |
Get |
Obsolete.
Gets a pointer to a runtime-generated function that marshals a call from managed to unmanaged code. |
Get |
Retrieves a MemberInfo object for the specified virtual function table (v-table or VTBL) slot. |
Get |
Obsolete.
Converts an object to a COM VARIANT. |
Get |
Obsolete.
Converts an object of a specified type to a COM VARIANT. |
Get |
Returns an instance of a type that represents a COM object by a pointer to its IUnknown interface. |
Get |
Obsolete.
Converts a COM VARIANT to an object. |
Get |
Obsolete.
Converts a COM VARIANT to an object of a specified type. |
Get |
Obsolete.
Converts an array of COM VARIANTs to an array of objects. |
Get |
Obsolete.
Converts an array of COM VARIANTs to an array of a specified type. |
Get |
Gets the system error message for the supplied error code. |
Get |
Gets the first slot in the virtual function table (v-table or VTBL) that contains user-defined methods. |
Get |
Obsolete.
Converts a fiber cookie into the corresponding Thread instance. |
Get |
Returns a managed object of a specified type that represents a COM object. |
Get |
Converts an unmanaged ITypeInfo object into a managed Type object. |
Get |
Returns the type associated with the specified class identifier (CLSID). |
Get |
Retrieves the name of the type represented by an ITypeInfo object. |
Get |
Obsolete.
Retrieves the name of the type represented by an ITypeInfo object. |
Get |
Retrieves the library identifier (LIBID) of a type library. |
Get |
Obsolete.
Retrieves the library identifier (LIBID) of a type library. |
Get |
Retrieves the library identifier (LIBID) that is assigned to a type library when it was exported from the specified assembly. |
Get |
Retrieves the LCID of a type library. |
Get |
Obsolete.
Retrieves the LCID of a type library. |
Get |
Retrieves the name of a type library. |
Get |
Obsolete.
Retrieves the name of a type library. |
Get |
Retrieves the version number of a type library that will be exported from the specified assembly. |
Get |
Creates a unique Runtime Callable Wrapper (RCW) object for a given IUnknown interface. |
Get |
Obsolete.
Gets a pointer to a runtime-generated function that marshals a call from unmanaged to managed code. |
Init |
Initializes the underlying handle of a newly created SafeHandle to the provided value. |
Is |
Indicates whether a specified object represents a COM object. |
Is |
Indicates whether a type is visible to COM clients. |
Num |
Calculates the number of bytes in unmanaged memory that are required to hold the parameters for the specified method. |
Offset |
Obsolete.
Returns the field offset of the unmanaged form of the managed class. |
Offset |
Returns the field offset of the unmanaged form of a specified managed class. |
Prelink(Method |
Executes one-time method setup tasks without calling the method. |
Prelink |
Performs a pre-link check for all methods on a class. |
Ptr |
Allocates a managed String, copies a specified number of characters from an unmanaged ANSI or UTF-8 string into it, and widens each character to UTF-16. |
Ptr |
Copies all characters up to the first null character from an unmanaged ANSI or UTF-8 string to a managed String, and widens each character to UTF-16. |
Ptr |
Allocates a managed String and copies the specified number of characters from a string stored in unmanaged memory into it. |
Ptr |
Allocates a managed String and copies all characters up to the first null character from a string stored in unmanaged memory into it. |
Ptr |
Allocates a managed String and copies a binary string (BSTR) stored in unmanaged memory into it. |
Ptr |
Allocates a managed String and copies a specified number of characters from an unmanaged Unicode string into it. |
Ptr |
Allocates a managed String and copies all characters up to the first null character from an unmanaged Unicode string into it. |
Ptr |
Allocates a managed String and copies a specified number of bytes from an unmanaged UTF8 string into it. |
Ptr |
Allocates a managed String and copies all characters up to the first null character from an unmanaged UTF-8 string into it. |
Ptr |
Obsolete.
Marshals data from an unmanaged block of memory to a managed object. |
Ptr |
Obsolete.
Marshals data from an unmanaged block of memory to a newly allocated managed object of the specified type. |
Ptr |
Marshals data from an unmanaged block of memory to a managed object of the specified type. |
Ptr |
Marshals data from an unmanaged block of memory to a newly allocated managed object of the type specified by a generic type parameter. |
Query |
Requests a pointer to a specified interface from a COM object. |
Read |
Reads a single byte at a given offset (or index) from unmanaged memory. |
Read |
Reads a single byte from unmanaged memory. |
Read |
Obsolete.
Reads a single byte at a given offset (or index) from unmanaged memory. |
Read |
Reads a 16-bit signed integer at a given offset from unmanaged memory. |
Read |
Reads a 16-bit signed integer from unmanaged memory. |
Read |
Obsolete.
Reads a 16-bit signed integer at a given offset from unmanaged memory. |
Read |
Reads a 32-bit signed integer at a given offset from unmanaged memory. |
Read |
Reads a 32-bit signed integer from unmanaged memory. |
Read |
Obsolete.
Reads a 32-bit signed integer at a given offset from unmanaged memory. |
Read |
Reads a 64-bit signed integer at a given offset from unmanaged memory. |
Read |
Reads a 64-bit signed integer from unmanaged memory. |
Read |
Obsolete.
Reads a 64-bit signed integer at a given offset from unmanaged memory. |
Read |
Reads a processor native sized integer at a given offset from unmanaged memory. |
Read |
Reads a processor native-sized integer from unmanaged memory. |
Read |
Obsolete.
Reads a processor native sized integer from unmanaged memory. |
Re |
Resizes a block of memory previously allocated with AllocCoTaskMem(Int32). |
Re |
Resizes a block of memory previously allocated with AllocHGlobal(IntPtr). |
Release(Int |
Decrements the reference count on the specified interface. |
Release |
Decrements the reference count of the Runtime Callable Wrapper (RCW) associated with the specified COM object. |
Release |
Obsolete.
Releases the thread cache. |
Secure |
Allocates an unmanaged binary string (BSTR) and copies the contents of a managed SecureString object into it. |
Secure |
Copies the contents of a managed SecureString object to a block of memory allocated from the unmanaged COM task allocator. |
Secure |
Copies the contents of a managed SecureString object to a block of memory allocated from the unmanaged COM task allocator. |
Secure |
Copies the contents of a managed SecureString into unmanaged memory, converting into ANSI format as it copies. |
Secure |
Copies the contents of a managed SecureString object into unmanaged memory. |
Set |
Sets data referenced by the specified key in the specified COM object. |
Set |
Sets the last platform invoke error on the current thread. |
Set |
Sets the last system error on the current thread. |
Size |
Obsolete.
Returns the unmanaged size of an object in bytes. |
Size |
Obsolete.
Returns the size of an unmanaged type in bytes. |
Size |
Returns the size of an unmanaged type in bytes. |
Size |
Returns the unmanaged size of an object of a specified type in bytes. |
String |
Allocates a BSTR and copies the contents of a managed String into it. |
String |
Copies the contents of a managed String to a block of memory allocated from the unmanaged COM task allocator. |
String |
Copies the contents of a managed String to a block of memory allocated from the unmanaged COM task allocator. |
String |
Copies the contents of a managed String to a block of memory allocated from the unmanaged COM task allocator. |
String |
Copies the contents of a managed String to a block of memory allocated from the unmanaged COM task allocator. |
String |
Copies the contents of a managed String into unmanaged memory, converting into ANSI format as it copies. |
String |
Copies the contents of a managed String into unmanaged memory, converting into ANSI format if required. |
String |
Copies the contents of a managed String into unmanaged memory. |
Structure |
Obsolete.
Marshals data from a managed object to an unmanaged block of memory. |
Structure |
Marshals data from a managed object of a specified type to an unmanaged block of memory. |
Throw |
Throws an exception with a specific failure HRESULT, based on the specified IErrorInfo interface. |
Throw |
Throws an exception with a specific failure HRESULT value. |
Unsafe |
Obsolete.
Gets the address of the element at the specified index inside the specified array. |
Unsafe |
Gets the address of the element at the specified index in an array of a specified type. |
Write |
Writes a single byte value to unmanaged memory. |
Write |
Writes a single byte value to unmanaged memory at a specified offset. |
Write |
Obsolete.
Writes a single byte value to unmanaged memory at a specified offset. |
Write |
Writes a character as a 16-bit integer value to unmanaged memory. |
Write |
Writes a 16-bit integer value to unmanaged memory. |
Write |
Writes a 16-bit signed integer value to unmanaged memory at a specified offset. |
Write |
Writes a 16-bit signed integer value into unmanaged memory at a specified offset. |
Write |
Obsolete.
Writes a 16-bit signed integer value to unmanaged memory at a specified offset. |
Write |
Obsolete.
Writes a 16-bit signed integer value to unmanaged memory at a specified offset. |
Write |
Writes a 32-bit signed integer value into unmanaged memory at a specified offset. |
Write |
Writes a 32-bit signed integer value to unmanaged memory. |
Write |
Obsolete.
Writes a 32-bit signed integer value to unmanaged memory at a specified offset. |
Write |
Writes a 64-bit signed integer value to unmanaged memory at a specified offset. |
Write |
Writes a 64-bit signed integer value to unmanaged memory. |
Write |
Obsolete.
Writes a 64-bit signed integer value to unmanaged memory at a specified offset. |
Write |
Writes a processor native-sized integer value to unmanaged memory at a specified offset. |
Write |
Writes a processor native sized integer value into unmanaged memory. |
Write |
Obsolete.
Writes a processor native sized integer value to unmanaged memory. |
Zero |
Frees a BSTR pointer that was allocated using the SecureStringToBSTR(SecureString) method. |
Zero |
Frees an unmanaged string pointer that was allocated using the SecureStringToCoTaskMemAnsi(SecureString) method. |
Zero |
Frees an unmanaged string pointer that was allocated using the SecureStringToCoTaskMemUnicode(SecureString) method. |
Zero |
Frees an unmanaged string pointer that was allocated using the StringToCoTaskMemUTF8(String) method. |
Zero |
Frees an unmanaged string pointer that was allocated using the SecureStringToGlobalAllocAnsi(SecureString) method. |
Zero |
Frees an unmanaged string pointer that was allocated using the SecureStringToGlobalAllocUnicode(SecureString) method. |
Product | Versions |
---|---|
.NET | Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9 |
.NET Framework | 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1 |
.NET Standard | 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1 |
UWP | 10.0 |
.NET feedback
.NET is an open source project. Select a link to provide feedback: