How should I release a DirectX11 texture created in a native plugin?

I’ve written a native plugin using DirectX11 that creates and updates textures. I’m creating the texture in C++ using CreateTexture2D() with D3D11_USAGE_DYNAMIC and I pass the result of CreateShaderResourceView() to Unity. I can update the texture using Map/UnMap or UpdateSubResource and it works perfectly.

However, it’s not obvious how I’m supposed to clean up after myself: if I call Release on the texture or resource view, Unity crashes because it may still be rendering that texture.

Unity’s Texture2D.CreateExternalTexture presumably doesn’t call AddRef() but does it call Release() at shutdown or when the texture is Destroyed? Can I just hand off the texture to Unity and assume it’ll clean up for me?

I can’t say that this is the “standard” way of doing it, but what works for me is:

  1. All materials with a reference to the external texture have that reference set to null (e.x. renderer.material.maintexture = null;)
  2. The ID3D11Texture2D is released (e.x. pTex->Release())
  3. The ID3D11ShaderResourceView is released (e.x. srv->Release())