Proper IntPtr use in C#

后端 未结 4 1353
生来不讨喜
生来不讨喜 2020-12-31 08:36

I think I understand the use of IntPtr, though I\'m really not sure.

I copied the IDisposable pattern from MSDN just to see what I could get from it, and w

4条回答
  •  死守一世寂寞
    2020-12-31 08:46

    An IntPtr is only a value type which size matches the size of a pointer on the target platform. You need to use it mainly when dealing with unmanaged pointers. An IntPtr itself cannot be disposed, because it only represents a location in memory. Your cleanup needs to be specific to the object referred to by the IntPtr. Say you have an unmanaged function that needs a window handle to do its work. In this case you can use the property Control.Handle to get a pointer to the window handle of the control. To properly cleanup the control and its underlying window you do not have to take care of the IntPtr refering to the unmanaged handle, but instead dispose the control.

    [DllImport("UnmanagedLibrary.dll")]
    private static void DoSomethingWithWindowHandle(IntPtr windowHandle);
    
    private void Foo()
    {
        Form form = new Form();
        // ...
        DoSomethingWithWindowHandle(form.Handle);
        // ...
        form.Dispose();
    }
    

提交回复
热议问题