views:

106

answers:

3

I've often heard about "handles", what exactly are those?

Edit: For instance I have heard about: windows handles event handles file handles

and so on. Are those things the same? Or they are some abstract terms?

+1  A: 

Handles are pointers to unmanaged resources like file handles, database connection handles, windows handles, etc... As they are handles to unmanaged resources in most cases they won't be automatically garbage collected and you need to ensure to properly release them or you might hear about leaking handles.

Darin Dimitrov
+1 In windows OS commonly they are 2byte of integers and in managed code you can work by them use IntPtr.
Jalal Amini
They aren't necessarily pointers, although they _can_ be. They are opaque identifiers.
Longpoke
+3  A: 

A "handle" is another name for a reference to a resource which is managed by the programmer explicitly instead of automatically by the runtime.

maerics
+2  A: 

A handle is an indirect way to reference an object owned by the OS or a library. When the operating system or a library owns an object but wants to let a client refer to it, it can provide a reference to that object called a handle.

Handles can be implemented in different ways. Typically they are not references in the C++ or C# sense. Often they are pointers cast to some opaque type, or they might be (or contain) an index into a table of objects that are owned by the operating system or library.

For example, in Windows, if you create a window, the OS creates an object that represents the window, but it doesn't return a pointer to that object. Instead, it returns a window handle, which provides an extra layer of indirection. When you pass the window handle back in another OS call, the OS knows which window object to use based on the handle. This prevents your code from directly accessing the window object.

The extra layer of indirection allows the OS or library to do things like move objects around, reference count the objects, and generally control what happens to the object. Like the PIMPL idiom, the implementation may change completely while still preserving the original API and thus not forcing clients to recompile. It's especially useful if you're trying to offer a non-object-oriented API for clients written in procedural languages like C.

Adrian McCarthy