In general, you shouldn’t need to worry about memory management in .NET, as objects will be garbage collected as needed.
That said, if you are creating .NET classes that hold onto unmanaged pointers, then you will want to make sure the memory allocated for the C++ objects is recovered when the .NET objects are disposed. You do this by inheriting your .NET classes from IDisposable, as it provides a mechanism for releasing unmanaged resources.
For example, let’s say your C++ library has a
CMyClass class object and in .NET you want to represent this as
MyClass. You could define
MyClass like this:
public class MyClass : IDisposable
IntPtr m_ptr; // CMyClass*
m_ptr = UnsafeNativeMethods.CMyClass_New();
#region IDisposable implementation
/// Passively reclaims unmanaged resources when the class user did not explicitly call Dispose().
// Passively reclaims unmanaged resources when the
// class user did not explicitly call Dispose().
/// Actively reclaims unmanaged resources that this instance uses.
public void Dispose()
// Actively reclaims unmanaged resources that this instance uses.
/// This method is called with argument true when class user calls Dispose(),
/// while with argument false when the Garbage Collector invokes the finalizer,
/// or Finalize() method. You must reclaim all used unmanaged resources in both cases,
/// and can use this chance to call Dispose on disposable fields if the argument is true.
/// Also, you must call the base virtual method within your overriding method.
protected virtual void Dispose(bool disposing)
if (m_ptr != IntPtr.Zero)
m_ptr = IntPtr.Zero;
The two unsafe native methods would look like this:
SDK_C_FUNCTION CMyClass* CMyClass_New()
return new CMyClass();
SDK_C_FUNCTION void CMyClass_Delete(CMyClass* ptr)
if (nullptr != ptr)
Does this help?