I have a .Net class that allocates unmanaged memory for a struct using Marshal.AllocHGlobal and then disposes of it using Marshal.FreeHGlobal.
I understand that the classes Microsoft.Win32.SafeHandles provide wrappers that handle this, but it isn't clear how to instantiate them (many don't have constructors) - should I be writing a specific implementation of the abstract base class or is there some way to use them in the extern declaration?
The main problem of subclassing
SafeHandleis that toMarshal.DestroyStructureyou need theTypeof the struct... This makes everything more complex.You can't use generics (because they aren't compatible with pinvoke)... So you can have multiple
SafeHandlesubclasses (one for eachType), or a property inside theSafeHandlewith the type of the struct that you set manually... Or you can make the constructor of theSafeHandleaccept the struct to be marshaled and set theTypeinside a property.I'm using the last two "options" (property
Typethat can be set manually or that can be set automatically by a constructor)Example of
MySafeHandle:The constructor you should use is the one that marshals the structure with
Marshal.StructureToPtr. It has the advantage that it saves the type of the structure so that it can use it later toMarshal.DestroyStructure.