[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.
untested:
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);
	}
}
[DllImport("libc")]
static extern IntPtr calloc (int nmemb, int size);
const int GMEM_ZEROINIT = 0x40;
[DllImport("kernel32")]
static extern IntPtr GlobalAlloc (int flags, int bytes);
On both platforms the memory can be released with Marshal.FreeHGlobal.
Robert
    
    
More information about the Mono-devel-list
mailing list