[Mono-dev] Allocating unmanaged memory

Robert Jordan robertj at gmx.net
Thu Jan 4 07:47:02 EST 2007

Leszek Ciesielski wrote:
> Hi,
> I need to allocate unmanaged memory AND make sure it is filled with
> 0's. Is there some clever/fast way to do this?  So far, I found only
> Marshal.WriteByte, which sets one byte at a time.


public static IntPtr Alloc (int bytes)
	int p = (int) Environment.OSVersion.Platform;
         if ((p == 4) || (p == 128)) {
		// unix
		return calloc (bytes, 1);
	} else {
		return GlobalAlloc (GMEM_ZEROINIT, bytes);

static extern IntPtr calloc (int nmemb, int size);

const int GMEM_ZEROINIT = 0x40;

static extern IntPtr GlobalAlloc (int flags, int bytes);

On both platforms the memory can be released with Marshal.FreeHGlobal.


More information about the Mono-devel-list mailing list