"Managed" (Compiled Type)

"Managed"::[t]

represents a composite type that adds automatic memory management to t.

Details

  • "Managed" adds memory management to types, such as those exposed by external libraries.
  • t cannot already have automatic memory management.
  • "Managed" uses automatic reference counting to automatically free objects that are no longer in use.
  • Managed objects returned from compiled code continue to be memory managed by the Wolfram Language kernel.
  • Managed objects are automatically unwrapped when passed as arguments to functions declared by LibraryFunctionDeclaration. »

Constructors

  • CreateTypeInstance["Managed"::[t],obj,freeFunc] constructs a managed object containing obj, which executes freeFunc[obj] when the "Managed" object is freed. freeFunc must have the type signature {t}"Null".
  • CreateTypeInstance["Managed"::[t],obj] uses DeleteObject as the freeFunc.
  • There are many constructors for specific "Managed"::[t] types, which are documented on the page for the compiled type t. For example, constructors for "Managed"::["CString"] are documented with "CString".

Properties

  • Information[man,"BaseType"] for man of type "Managed"::[t] gives "TypeSpecifier"::[t].
  • UnmanageObject unwraps and invalidates a managed object, taking ownership of the wrapped object.

Conversions

    Expressions

  • "Managed" objects are converted to memory-managed expressions. When the expression is freed, the freeing function of the original managed object is executed.

Runtime Errors

    InvalidManaged

  • Using a managed object after it has been unmanaged with UnmanageObject can give a runtime error.

Examples

open allclose all

Basic Examples  (2)

Compile a program that returns a managed "CString" object:

The wrapped "CString" is automatically freed when the managed object goes out of scope:

Compile a function that returns a managed object that prints when it is freed:

Create the managed object and then let it pass out of scope:

Scope  (4)

Managed objects are memory managed in compiled code:

The contents of managed objects can be accessed with UnmanageObject:

Create a managed object:

Extract its contents with UnmanageObject:

UnmanageObject invalidates the managed object, so subsequent calls to UnmanageObject fail:

Managed objects that have been unmanaged are not automatically freed. Compile functions for creating and unmanaging a managed object:

Create a managed object and then let it pass out of scope:

Unmanage the object before letting it pass out of scope:

Represent a function that takes an unmanaged C array as an argument:

The managed C array is borrowed and automatically unwrapped before it is passed to the library function: