开发者

How to use SafeWaitHandle.DangerousGetHandle?

I have unmanaged code that calls an asynchronous managed method that returns a handle, and then the unmanaged code uses that handle to wait. According to the documentation, SafeWaitHandle provid开发者_JS百科es 2 other methods (DangerousAddRef and DangerousRelease ). Should I use these methods in order to prevent the Handle from not being released? As the name of the method DangerousGetHandle suggest, it seems to me that I should be very careful with something, what is so dangerous here?

Edit: Is there a better way to implement this scenario (not dangerously)?


If the managed method returns the handle, but doesn't pass ownership of the handle to the calling unmanaged method, then you should just return the handle as a SafeWaitHandle directly (it will be marshalled to a handle) - this way unmanaged code doesn't have to worry about releasing the handle.
If you want to pass ownership of the handle to the unmanaged method, then you should call DangerousAddRef before returning the handle, but then you have to release the handle using unmanaged code.


From MSDN:

Using the DangerousGetHandle method can pose security risks because, if the handle has been marked as invalid with SetHandleAsInvalid, DangerousGetHandle still returns the original, potentially stale handle value. The returned handle can also be recycled at any point. At best, this means the handle might suddenly stop working. At worst, if the handle or the resource that the handle represents is exposed to untrusted code, this can lead to a recycling security attack on the reused or returned handle.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜