All notes
Marshalling

References

IntPtr


[SerializableAttribute]
[ComVisibleAttribute(true)]
public struct IntPtr : ISerializable

Assembly: mscorlib.

A platform-specific type that is used to represent: 1 - a pointer, or 2 - a handle.

The IntPtr type is designed to be an integer whose size is platform-specific. That is, an instance of this type is expected to be 32-bits on 32-bit hardware and operating systems, and 64-bits on 64-bit hardware and operating systems.

The IntPtr type can be used as a common means of referring to data between languages that do and do not support pointers.

IntPtr objects can also be used to hold handles. For example, instances of IntPtr are used extensively in the System.IO.FileStream class to hold file handles.

While obtaining a value for the IntPtr (e.g. calling P/Invoked function) may require the appropriate security permissions, there is no unsafe code required.


int test = 55;

// Allocating memory for int
IntPtr intPointer = Marshal.AllocHGlobal(sizeof(int));

Marshal.WriteInt32(intPointer,test);

// sending intPointer to unmanaged code here

//Test reading of IntPtr object
int test2 = Marshal.ReadInt32(intPointer); // test2 would be equal 55

// Free memory
Marshal.FreeHGlobal(intPointer);

It is typically used to wrap a pointer or handle to be handed off to an unmanaged function as you have done.


[DllImport("UnmanagedLibrary.dll")]
private static void DoSomethingWithWindowHandle(IntPtr windowHandle);

private void Foo()
{
    Form form = new Form();
    // ...
    DoSomethingWithWindowHandle(form.Handle);
    // ...
    form.Dispose();
}

Marshal

Namespace: System.Runtime.InteropServices
Assembly: mscorlib

AddRef(IntPtr)  // Increment the reference count by one.
Release(IntPtr)	// Decrements the reference count.

AllocHGlobal(Int32) // Allocates memory from the unmanaged memory of the process.
AllocHGlobal(IntPtr)  // IntPtr: the pointer to the specified number of bytes.
FreeHGlobal(IntPtr)

ReadByte(IntPtr) // Reads a single byte from unmanaged memory.

// NOTE: IntPtr indicates unmanaged memory.
Copy(Byte[], Int32 startIndex, IntPtr, Int32 length)	// Copies data from managed Byte array to an unmanaged memory pointer.
Copy(IntPtr, Byte[], Int32 startIndex, Int32 length)	// Copies data from an unmanaged memory pointer to a managed 8-bit unsigned integer array.