Re: Safe handles and Marshal class
Peter Obiefuna <[email protected]> Tue, 12 Feb 2008 14:59:18 -0700
| Newsgroups | gmane.comp.windows.devel.dotnet.clr |
|---|---|
| Message-ID | <[email protected]> |
Alex, I have a suggestion to take you from where you are to where you are
after:
1. CreateSafeMemoryHandle that implements IDisposable
2. Let Dispose() implement your finally code.
3. let create a field called 'buffer'.
4. Implement a constructor that takes 'size' and assigns field with
Marshal.AllocHGlobal(size)
5. Implement another constructor that takes an IntPtr (this could be private
if you care).
6. Overload the = operator to call the constructor in 5. and assign the
'buffer' field.
Then, you can do using(bla a = new bla(500)){...} or using (bla b =
Marshall.Alloc(500)){...}
P
--------------------------------------------------
From: "Alex Ivanoff" <[email protected]>
Sent: Tuesday, February 12, 2008 1:44 PM
To: <[email protected]>
Subject: Re: [DOTNET-CLR] Safe handles and Marshal class
> This is the pattern I use today:
>
> IntPtr buffer = IntPtr.Zero;
> try
> {
> buffer = Marshal.AllocHGlobal(size);
> ...
> }
> finally
> {
> if (buffer != IntPtr.Zero)
> {
> Marshal.FreeHGLobal(buffer);
> }
> }
>
> And this is what I am after:
>
> using (SafeMemoryHandle buffer = Marshal.SafeAllocHGlobal())
> {
> ...
> }
>
> Where SafeMemoryHandle is SafeHandle-derived class.
>
>
> -----Original Message-----
> From: Discussion of development on the .NET platform using any managed
> language [mailto:[email protected]] On Behalf Of Peter
> Ritchie
> Sent: Tuesday, February 12, 2008 13:39
> To: [email protected]
> Subject: Re: [DOTNET-CLR] Safe handles and Marshal class
>
> In what context? Are you looking for something to
> automatically/deterministically free native memory that you've manually
> allocated?
>
> ===================================
> This list is hosted by DevelopMentor® http://www.develop.com
>
> View archives and manage your subscription(s) at
> http://discuss.develop.com
>
===================================
This list is hosted by DevelopMentor® http://www.develop.com
View archives and manage your subscription(s) at http://discuss.develop.com