Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
464 views
in Technique[技术] by (71.8m points)

.net - IntPtr, SafeHandle and HandleRef - Explained

Without pointing me to MSDN, could someone give a concise, clear explanation of the purpose of each of these and when to use them. (IntPtr, SafeHandle and HandleRef)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

IntPtr is just a simple integer-based struct that can hold a pointer (ie., 32 bit size on 32-bit systems, 64-bit size on 64-bit systems).

SafeHandle is a class that is intended to hold Win32 object handles - it has a finalizer that makes sure that the handle is closed when the object is GC'ed. SafeHandle is an abstract class because different Win32 handles have different ways they need to be closed. Prior to the introduction of SafeHandle, IntPtr was used to hold Win32 handles, but ensuring that they were properly closed and prevented from being GC'ed was the responsibility of the programmer.

HandleRef is a way to make sure that an unmanaged handle is not GC'ed when you're in the middle of a P/Invoke call. Without something like HandleRef, if your managed code doesn't do anything with the handle after the P/Invoke call, if the GC were run during the P/Invoke call it would not realize that the handle was still in use and might GC it. I imagine (but I'm not sure and haven't looked) that SafeHandle might use HandleRef as part of its management of the encapsulated handle.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...