Question

Why is Matrix a heavyweight class derived from MarshalByRefObject instead of a lightweight struct?

Was it helpful?

Solution

The Matrix class is actually a wrapper to an unmanaged structure which is manipulated by the GDI+ Flat API.

That said, it's common for the classes in the System.Drawing namespace to derive from the MarshalByRefObject class for the convenience of an IDisposable implementation as well as get automatic marshaling across the application domain boundary when used in Remoting.

This was more than likely done because most of the GDI functions (which most of the APIs that the Windows Forms controls rely on) will use the GDI matrix for transformations; using a lightweight, fully managed code structure would require translation of that structure across the managed/unmanaged boundary every time a method was called.

Compared to the cost of marshaling just the call and the handle, versus the call and the entire structure whenever you want to do operations on the matrix, it was probably decided that for performance reasons it was better to marshal the calls.

OTHER TIPS

For the usual reason, it is an unmanaged object. It has a finalizer too, in case you forget to dispose.

GDI+ is at its core a native api. The corresponding header for C++ programs is <gdiplus.h>, you'll find it in the Windows SDK include directory. The MSDN Library article for the native Matrix class is here.

According to MSDN documentation for the method:

Calling Dispose allows the resources used by this Matrix object to be reallocated for other purposes.

Quick look through reflector shows this code:

private void Dispose(bool disposing)
{
  if (!(this.nativeMatrix != IntPtr.Zero))
    return;
  SafeNativeMethods.Gdip.GdipDeleteMatrix(new HandleRef((object) this, this.nativeMatrix));
  this.nativeMatrix = IntPtr.Zero;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top