Table of Contents

Class SafeGCHandle

Namespace
Ubiquity.NET.InteropHelpers
Assembly
Ubiquity.NET.InteropHelpers.dll

Helper type to wrap GC handles with ref counting

public sealed class SafeGCHandle : SafeHandle, IDisposable
Inheritance
SafeGCHandle
Implements
Inherited Members

Remarks

Instances of this class (as a private member of a controlled type) help to ensure the referenced object stays alive while in use for native ABI as a "context" for callbacks. This is the key to ref counted behavior to hold 'o' (and anything it references) alive for the GC. The "ownership" of the refcount is handed to native code while the calling code is free to no longer reference the containing instance as it holds an allocated GCHandle for itself and THAT is kept alive by a ref count that is "owned" by native code.

This is used as a member of such a holding type so that 'AddRefAndGetNativeContext' retrieves a marshaled GCHandle for the containing/Controlling instance that is then provided as the native "Context" parameter.

It is assumed that instances of this type are held in a disposable type such that when the containing type is disposed, then this is disposed. Additionally, this assumes that the native code MIGHT dispose of this instance and that callers should otherwise account for the ref count increase to hold the instance alive. That is, by holding a GCHandle to self, with an AddRef'd handle the instance would live until the app is terminated! Thus applications using this MUST understand the native code use and account for the disposable of any instances with this as a member. Typically a callback provided to the native code is used to indicate release of the resource. That callback will call dispose to decrement the refcount on the handle. If the ref count lands at 0, then the object it refers to is subject to normal GC.

Constructors

SafeGCHandle(object)

Initializes a new instance of the SafeGCHandle class.

Properties

IsInvalid

When overridden in a derived class, gets a value indicating whether the handle value is invalid.

Methods

AddRefAndGetNativeContext()

Adds a ref count to this handle AND converts the allocated GCHandle for use in native code

ReleaseHandle()

When overridden in a derived class, executes the code required to free the handle.