string text = "Hello, world!"; byte[] buffer = Encoding.UTF8.GetBytes(text); IntPtr p = Marshal.AllocCoTaskMem(buffer.Length); Marshal.Copy(buffer, 0, p, buffer.Length); // Use the pointer p here Marshal.FreeCoTaskMem(p);
public static IntPtr GetIntPtrFromObject(object obj) { GCHandle handle = GCHandle.Alloc(obj, GCHandleType.Pinned); IntPtr ptr = handle.AddrOfPinnedObject(); handle.Free(); return ptr; }This example shows a helper function that takes an object as input, pins it so that the garbage collector won't move it around, and returns a pointer to the object's memory location. The package library used here is the System.Runtime.InteropServices namespace.