Can I use SafeHandle instead of IntPtr?

Viewed 14707

I've searched the internet far and wide but didn't find a good explanation.

My question is pretty simple.

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):

[DllImport(MyDll)]
static extern bool Initialize([In] string name, out IntPtr handle);

The signature in the DLL itself is written as: Initialize(LPTSTR name, HANDLE handle) with the comment "HANDLE: Pointer to a location that will receive the handle".

And subsequent calls are in the form of

[DllImport(MyDll)]
static extern bool DoSomething(IntPtr handle, uint randomParameter);

I have been reading about SafeHandle 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?

1 Answers
Related