Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>When you call <code>makeNewHandleOfA</code>, you <strong>own</strong> the returned instance, so you must release it. When you call <code>getHandleOfA</code>, you <strong>do not own</strong> the returned instance, but you still want to manage its lifecyle (ie: prevent the underlying native library from releasing it).</p> <p>It means you basically want different Release strategies for those two use cases.</p> <p><strong>Option 1</strong></p> <p>With:</p> <pre><code>internal class MyOwnedSafeHandleA : MySafeHandleA { protected override bool ReleaseHandle() { releaseHandleToA(handle); return true; } } internal class MySafeHandleA : SafeHandle { private int refCountIncremented; internal void IncrementRefCount(Action&lt;MySafeHandleA&gt; nativeIncrement) { nativeIncrement(this); refCountIncremented++; } protected override bool ReleaseHandle() { while (refCountIncremented &gt; 0) { releaseHandleToA(handle); refCountIncremented--; } return true; } } </code></pre> <p>You can declare your DllImports like so:</p> <pre><code> [DllImport("somedll.dll")] public extern MyOwnedSafeHandleA makeNewHandleOfA(); [DllImport("somedll.dll")] private extern MySafeHandleA getHandleOfA(MySafeHandleB handleToB, int index); [DllImport("somedll.dll")] private extern void addRefHandleToA(MySafeHandleA handleToA); </code></pre> <p><strong>Option 2</strong></p> <p>You could declare your SafeHandle like this:</p> <pre><code>internal class MySafeHandleA : SafeHandle { MySafeHandleA(IntPtr handle) : base(IntPtr.Zero, true) { SetHandle(handle); } protected override bool ReleaseHandle() { releaseHandleToA(handle); return true; } } </code></pre> <p>And use it like so:</p> <pre><code>[DllImport("somedll.dll"] private extern IntPtr getHandleOfA(MySafeHandleB handleToB, int index); [DllImport("somedll.dll"] private extern void addRefHandleToA(IntPtr ptr); public MySafeHandleA _getHandleOfA(MySafeHandleB handleToB, int index) { IntPtr ptr = getHandleOfA(handleToB, index); addRefHandleToA(ptr); return new MySafeHandleA(ptr); } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload