title: Can I use SafeHandle instead of IntPtr?
body: <p>I've searched the internet far and wide but didn't find a good explanation.</p>
  
  <p>My question is pretty simple.</p>
  
  <p>I have a DLL which has a function called Initialize and one of the parameters is a pointer that will receive a handle to be used with subsequent calls. Another parameter is a string which I will list for completeness. The signature I'm using is (in its simple form):</p>
  
  <pre><code>[DllImport(MyDll)]
  static extern bool Initialize([In] string name, out IntPtr handle);
  </code></pre>
  
  <p>The signature in the DLL itself is written as: <code>Initialize(LPTSTR name, HANDLE handle)</code> with the comment "HANDLE: Pointer to a location that will receive the handle".</p>
  
  <p>And subsequent calls are in the form of</p>
  
  <pre><code>[DllImport(MyDll)]
  static extern bool DoSomething(IntPtr handle, uint randomParameter);
  </code></pre>
  
  <p>I have been reading about <code>SafeHandle</code> and I was wondering if I could use it to substite for my IntPtr handle. And if I can, how do I do it? Extending the abstract SafeHandle class isn't an issue, but can I directly substitute my IntPtr for SafeHandle (and use default Marshalling) or do I need to do something extra?</p>