Reputation: 1549
I have read some documentation and here is the class, I'm using for IntPtr operations to make them more safe:
internal class MySafeHandleOperator : SafeHandleZeroOrMinusOneIsInvalid
{
public MySafeHandleOperator(IntPtr handle) : base(true)
{
SetHandle(handle);
}
public IntPtr GetPtr()
{
return this.handle;
}
protected override bool ReleaseHandle()
{
this.Dispose(true);
return true;
}
}
The main question is in ReleaseHandle method. I've used it in such way, but I'm instersted if this is a correct way of usage? May be there is another, right way to release a handle and clear this class?
I would like to use this class in a similar way to (a simple example):
Process p = Process.Start(processName);
MySafeHandleOperator mh = new MySafeHandleOperator(p.MainWindowHandle);
Would be grateful if someone would take a look and say if I'm doing everything right, or this method needs to be re-writed.
Upvotes: 2
Views: 2352
Reputation: 941705
No, that does not look good. The point of a SafeHandle is to ensure that your class object doesn't get destroyed while you passed the handle to native code. That can be nasty, your finalizer gets called and the native code continues using an invalid handle. Beyond the runtime failure and corruption that can cause, there is also the very scary handle recycling attack scenario that's enabled by this.
You however have absolutely no control over the lifetime of that window handle. You can't stop it from getting destroyed, nor can you do anything to destroy it yourself. Well, assuming that you are not going to kill a process with a finalizer. Something you could have found out by not having a useful override for ReleaseHandle(). Use, say, the SafeFileHandle class as an example of a practical derived class. The .NET Framework has many, a good decompiler is an excellent way to find them.
Long story short, since there is no point in wrapping it, IntPtr is fine
Upvotes: 5