JasonBock / WebAssembly.Generators

Source generators for the WebAssembly package.
MIT License
1 stars 1 forks source link

Capture Instance Object for Disposal #6

Closed JasonBock closed 3 years ago

JasonBock commented 3 years ago

The generated Create() method does something like this:

public static CollatzTest Create(string path = @"collatz.wasm") =>
  Compile.FromBinary<CollatzTest>(@"collatz.wasm")(new ImportDictionary()).Exports;

The return value from (new ImportDictionary()) returns a WebAssembly.Instance<> object, which implements IDisposable. Create() returns the value from the Exports property. Therefore, we need a way to return an object that is IDisposable but is of the generated type.

The idea is to change the generated type to something like this:

using System;
using WebAssembly;

public abstract class CollatzTest
  : IDisposable
{
  private Instance<CollatzTest>? capturedInstance;

  public abstract int collatz(int a0);

  public static CollatzTest Create(string path = @"collatz.wasm")
  {
    var instance = Compile.FromBinary<CollatzTest>(@"collatz.wasm")(new ImportDictionary());
    var exports = instance.Exports;
    exports.capturedInstance = instance;
    return exports;
  }

  public void Dispose() => this.capturedInstance?.Dispose();
}

The user can then put the returned object in a using block. If the user doesn't do this, or manually creates the instance themselves, the Instance<> has a finalizer that will release any memory, though this could increase memory pressure and make the GC work a bit harder.