Search code examples
.netc++comcom-interopidispatch

Need to duplicate an IDispatch* with .NET backing; don't know class name


I'm hosting a .NET library in my C++ program using the following methods, though not an exhaustive list:

CorBindToRuntimeEx()
GetDefaultDomain()
CreateInstance()
Invoke()

I have C++ classes which correspond to .NET classes. Each class instance contains a CComPtr<IDispatch>, which I use to call functions and get/set member variables.

That's working fine, except when I copy my C++ class, I end up with two C++ class instances that both point to the same .NET instance. When I change a variable value in one instance, it's reflected in the other.

So, I'd really like to duplicate my IDispatch pointer, so that each C++ class instance has one unique .NET class instance. I could call CreateInstance(), but for various reasons it's inconvenient to figure out the library and class names.

tl;dr
How can I duplicate my .NET backed IDispatch pointer without looking up the class/library names?

Thanks!


Solution

  • This is the expected behavior, the CComPtr copy constructor will simply copy the interface pointer and add a reference with AddRef(). There is no mechanism to automatically create a deep copy, neither in COM nor in .NET. This isn't fundamentally different from C++. There is a well-known interface defined in .NET, ICloneable. It barely escaped being deprecated, the interface doesn't have a way to let the caller specify that a deep copy instead of a shallow copy is desired. Making it next to useless and very rarely implemented. Doesn't help here anyway, COM doesn't have anything similar.

    Nope, you'll have to maintain enough state and write the code to create a new object. Do review your need for this. If you are making the C++ object copy solely with the intent to create a copy of the COM object (and its underlying .NET object) then you probably shouldn't be making that copy.