Click here to Skip to main content
Click here to Skip to main content
Go to top

C++/CLI HowTo : Deriving from a C# disposable class

, 5 Jul 2008
Rate this:
Please Sign up or sign in to vote.
This article walks through the implementation of a C++/CLI class from a disposable C# base.

Introduction

Last week at work, I had to work on a C++/CLI class that derived from a class written in C# which implemented IDisposable. I got it wrong at first (yeah, same guy who wrote a book on the subject a couple of years ago), and my boss and I spent some time going through the generated code in Reflector before fixing it up. I came home that night and quickly put together a simple project so I could see the whole picture from a simple perspective. I thought it would benefit others to put together an article reflecting (no pun intended) the issue.

The C# base class

Here's a simple C# class that implements IDisposable. It's assumed that the class handles both managed and native resources.

namespace DisposeDemo
{
    [SuppressMessage("Microsoft.Naming", 
        "CA1709:IdentifiersShouldBeCasedCorrectly", 
        MessageId = "Cs", 
        Justification = "Personal preference")]
    public class CsDisposableBase : IDisposable
    {
        #region IDisposable Members

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        ~CsDisposableBase()
        {
            Dispose(false);
        }

        /// <span class="code-SummaryComment"><summary></span>
        /// Derived classes need to override this appropriately
        /// <span class="code-SummaryComment"></summary></span>
        /// <span class="code-SummaryComment"><param name="disposing">Indicates whether this is a dispose call</span>
        /// or a call invoked from the finalzier<span class="code-SummaryComment"></param></span>
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                DisposeManagedResources();
            }

            FreeNativeResources();
        }

        #endregion

        private void DisposeManagedResources()
        {
            this.WriteLine("Disposing managed resources in base class");
        }

        private void FreeNativeResources()
        {
            this.WriteLine("Freeing native resources in base class");
        }

        public CsDisposableBase(String name)
        {
            this.Name = name;
        }

        public String Name { get; private set; }

        protected void WriteLine(String text)
        {
            Console.WriteLine("{0} : {1}", this.Name, text);
        }
    }
}

For any C# developer inheriting from this class, it's a no-brainer to override and implement void Dispose(bool) as the class requirements dictate. But things are not so obvious from C++/CLI. C++/CLI does not permit any method named "Dispose" in your class. While you've all probably implemented IDisposable classes in C++/CLI before, you may not have yet derived from a C# IDisposable base before. Anyway, the trick is to avoid over-thinking and complicating the issue - all you need to do is to handle it just as you'd do normally. Put the managed-disposal in the destructor and the native-disposal in the finalizer.

The C++/CLI derived class

Here's the derived class implementation in C++/CLI:

namespace CppDisposable
{
  public ref class DisposableDerived : CsDisposableBase
  {
  private:
    void DisposeManagedResourcesDerived()
    {
      WriteLine("Disposing managed resources in derived class");
    }

    void FreeNativeResourcesDerived()
    {
      WriteLine("Freeing native resources in derived class");
    }

  public:
    ~DisposableDerived()
    {
      DisposeManagedResourcesDerived();
      this->!DisposableDerived();
    }

    !DisposableDerived()
    {
      FreeNativeResourcesDerived();
    }

    DisposableDerived(String^ name) : CsDisposableBase(name)
    {
    }

  };
}

At first glance, the code seems wrong. How do we ensure that the base class disposal code (and the finalizer) are called as and when needed? Let's write some test code to see what happens.

int main(array<System::String ^> ^args)
{
  CppDisposable::DisposableDerived object1(
    "Object that gets disposed");

  CppDisposable::DisposableDerived^ object2 =
    gcnew CppDisposable::DisposableDerived("Object that gets GCd");
  return 0;
}

Running that gives the following output :-

Wow. Everything worked fine. How did that happen? The answer lies in VC++ compiler magic. A look at the generated code using Reflector shows us that the compiler has generated the code that we may otherwise have had to write ourselves.

What Reflector shows

Here's the generated code (as viewed in Reflector):

protected override void Dispose([MarshalAs(UnmanagedType.U1)] bool flag1)
{
    if (flag1)
    {
        try
        {
            this.~DisposableDerived();
        }
        finally
        {
            base.Dispose(true);
        }
    }
    else
    {
        try
        {
            this.!DisposableDerived();
        }
        finally
        {
            base.Dispose(false);
        }
    }
}

So, during a Dispose call, here's what will happen:

  1. The C# base class Dispose will call Dispose(true) and suppress GC.
  2. The C++/CLI implementation will call ~DisposableDerived (which frees the managed resources in the derived class and then calls !DisposableDerived which frees the native resources in the derived class).
  3. Now, base.Dispose(true) is called (in the finally-block) which frees the managed and native resources in the base class.

And this is what happens during a finalization:

  1. The C# base class finalizer calls Dispose(false).
  2. The C++/CLI implementation calls !DisposableDerived (which frees the native resources in the derived class).
  3. And base.Dispose(false) is called (in the finally-block) which frees the native resources in the base class.

Essentially, this code is exactly what we'd have needed to write - the compiler generates it for us.

Conclusion

I know this is a very simple article, but sometimes it's the simple things that we stumble over. I wish I had covered this topic in my book (where I talk about deterministic destruction). As always, please feel free to submit feedback (critical or otherwise).

History

  • July 5, 2008 - Article published.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Nish Sivakumar

United States United States
Nish is a real nice guy who has been writing code since 1990 when he first got his hands on an 8088 with 640 KB RAM. Originally from sunny Trivandrum in India, he has been living in various places over the past few years and often thinks it’s time he settled down somewhere.
 
Nish has been a Microsoft Visual C++ MVP since October, 2002 - awfully nice of Microsoft, he thinks. He maintains an MVP tips and tricks web site - www.voidnish.com where you can find a consolidated list of his articles, writings and ideas on VC++, MFC, .NET and C++/CLI. Oh, and you might want to check out his blog on C++/CLI, MFC, .NET and a lot of other stuff - blog.voidnish.com.
 
Nish loves reading Science Fiction, P G Wodehouse and Agatha Christie, and also fancies himself to be a decent writer of sorts. He has authored a romantic comedy Summer Love and Some more Cricket as well as a programming book – Extending MFC applications with the .NET Framework.
 
Nish's latest book C++/CLI in Action published by Manning Publications is now available for purchase. You can read more about the book on his blog.
 
Despite his wife's attempts to get him into cooking, his best effort so far has been a badly done omelette. Some day, he hopes to be a good cook, and to cook a tasty dinner for his wife.

Comments and Discussions

 
GeneralMy 5! PinmemberRakeshMeena13-Jun-11 22:14 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140905.1 | Last Updated 5 Jul 2008
Article Copyright 2008 by Nish Sivakumar
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid