[Mono-dev] Allocating unmanaged memory

Jon Chambers joncham at gmail.com
Thu Jan 4 07:59:26 EST 2007


Just a minor note, only recently has mono started using GlobalAlloc and
GlobalFree for the Marshal.*HGlobal routines on Windows. It was previously
using  g_free on all platforms. I think only the svn version currently has
this change, so I am not sure what will happen if you try to free the memory
on Windows using Marshal.FreeHGlobal with released versions of mono. You may
need to pinvoke GlobalFree yourself on windows to release the memory until
the next release of mono.

- Jonathan

On 1/4/07, Robert Jordan <robertj at gmx.net> wrote:
>
> 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
>
> _______________________________________________
> Mono-devel-list mailing list
> Mono-devel-list at lists.ximian.com
> http://lists.ximian.com/mailman/listinfo/mono-devel-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.ximian.com/pipermail/mono-devel-list/attachments/20070104/2138c72a/attachment.html 


More information about the Mono-devel-list mailing list