Question

Just a general question, take the following code from a WindowsForms application:

using System.Runtime.InteropServices;

protected override void WndProc(ref Message m)
{
    if (m.Msg == 0x216)  // WM_MOVING = 0x216
    {
        Rectangle rect = (Rectangle) Marshal.PtrToStructure(m.LParam, typeof (Rectangle));
        DoSomethingWithRect(rect);
    }
    base.WndProc(ref m);
}

Am I supposed to call Marshal.DestroyStructure(m.LParam) after DoSomethingWithRect in order to prevent a memory leak? I will be happy to get an explanation on why or why not.

Thanks.

Était-ce utile?

La solution

You don't need to do anything more than you have here. The unmanaged memory is owned by the system. It allocated it, and it will dispose of it.

You did not allocate any unmanaged memory. You simply copied the contents of the unmanaged struct that you were passed into a new managed struct. The .net GC will take take of the lifetime of that managed object.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top