File and Enumeration Contexts
Contexts are the placeholders for application-defined data. A context is held as a property within instances of CBFileInfo, CBHandleInfo, CBDirectoryEnumerationInfo and CbFsStreamEnumerationInfo classes. Contexts can be set in several event handlers (such as OnCreateFile, OnEnumerateDirectory etc) and used in several other event handlers. The data, placed to the Context, is not used by CBFS Connect in any way.
Contexts can be used to store information about the file or directory, and this information can be re-used later to speed-up subsequent operations.
For example, if you open some file on the file system, you can place file handle to Context. Next, when the application handles for example OnReadFile event, it can use this handle instead of the file name. This speeds-up the operation, because there is no need to search some hash tables for a handle of the file.
Another example is a reference to the list of files, which has been built during the first call to OnEnumerateDirectory.
Contexts are local to the process in which they were created. They can't be passed to other processes.
During directory enumeration, contexts live from the call to OnEnumerateDirectory to the call to OnCloseEnumeration.
Contexts of file operations live from file open to file close calls. Contexts are stored with the other information, related to the opened file or directory.
There exist two different contexts for file operations - first (so-called file context) is allocated on the first file open operation and is deallocated on the last file close operation. Another one (so-called handle context) is allocated for each file open operation and is deallocated during corresponding file close operation. For example, consider the following sequence of operations:
Note, that when CallAllOpenCloseCallbacks property is false, OnOpenFile event is fired only for step 1 above, and OnCloseFile is fired only on step 6. Consequently, handle contexts are useless (or you can treat them as having the same use as file contexts).
Use of Contexts in VCL and C++/Lib API is quite straightforward - you just put pointers to Context.
With .NET API, the situation is more complicated, as .NET uses garbage collection and improper typecasting can cause problems with object lifetime.
To avoid this problem, we have declared Contexts to be IntPtr. If you want to store the reference to the object in Context, you use GCHandle as follows (C# syntax):
Stream stream; // the object we put to Context
GCHandle ctx = GCHandle.Alloc(stream);
Context = (IntPtr) ctx;
GCHandle ctx = (GCHandle) Context;
Stream stream = (Stream ) ctx.Target; // the object we get from Context
To store numbers or other types, that are not objects, use "boxing" (.NET concept, when a value type is "packed" into an object).