Вопрос

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.

Это было полезно?

Решение

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top