Exception in finalizer of custom encoder

Environment

  • Pythonnet version: master
  • Python version: 3.7
  • Operating System: Windows 10

Details

I am using a custom encoder defined in Python to work around the conversion of IList to Python lists (see #963 (comment)):

# Prevent Python.NET from converting IList to Python lists
from Python.Runtime import PyObjectConversions
from Python.Runtime.Codecs import RawProxyEncoder
class  ListAsRawEncoder(RawProxyEncoder):
  __namespace__ = 'Python.Runtime.Codecs'
  def CanEncode(self, clr_type):
    return clr_type.Name == 'IList`1' and clr_type.Namespace == 'System.Collections.Generic'

list_encoder = ListAsRawEncoder()
PyObjectConversions.RegisterEncoder(list_encoder)

This works fine until I have called Python.Runtime.PythonEngine.Shutdown, and GC kicks in. Then there is this exception:

Unhandled exception
Exception thrown:
System.InvalidOperationException: Handle is not initialized.
   at System.Runtime.InteropServices.GCHandle.Free()
   at Python.Runtime.PythonDerivedType.Finalize(IPythonDerivedType obj)
   at Python.Runtime.Codecs.ListAsRawEncoder.Finalize()

The crash started happening after #958 was merged.