Info

Since ChangedFileDumper is a native class, it can be instantiated in any kind of unmanaged memory. This includes the C++ heap, the COM heap, and the stack. In all these cases, the GC would not be aware of the FileSystemWatcherA data member. Therefore, neither would the GC consider this tracking handle when the GC determines unreferenced objects, nor would this tracking handle data member be updated when the instance is relocated during garbage collection.

On the one hand, it is reasonable that the native class cannot have a field of type FileSystemWatcherA; on the other hand, the class ChangedFileDumper needs to refer to an instance of FileSystemWatcher so that different methods of ChangedFileDumper can access the same FileSystemWatcher instance. Visual C++ comes with a helper template called msclr::gcroot, which is defined in the header file msclr/gcroot.h. This helper allows you to solve this problem:

// ChangedFileDumper.cpp

// compile with "CL /c /clr ChangedFileDumper.cpp"

#include <msclr/gcroot.h> // required for msclr/gcroot.h using msclr::gcroot;

#using <System.dll>

using System::IO::FileSystemWatcher;

class ChangedFileDumper {

gcroot<FileSystemWatcherA> fsw;

The template gcroot has several members that allow you to access the object in a convenient way. It is often possible to treat a variable of type gcroot<FileSystemWatcherA> as if it were of type FileSystemWatcherA. For example, gcroot<FileSystemWatcherA> has a constructor that expects a parameter of type FileSystemWatcherA. This allows you to initialize a gcroot<FileSystemWatcherA> variable with a FileSystemWatcherA handle. The following code uses this constructor to implement the constructor of the class ChangedFileDumper:

ChangedFileDumper::ChangedFileDumper(std::string path)

Was this article helpful?

0 0

Post a comment