Using COM within .NET

T

Tommy Vercetti

I have a very simple COM object that I want to use within .NET. The COM
object was written in C++/ATL. The object works but the problem is the
COM object never seems to be released and the DLL files can never be
overwritten without restarting the computer.

MyLibrary.CMyCOMClass netWrappedCOMObj = new MyLibrary.CMyCOMClassClass();
try {
// Currently, not using the object, just create/dispose
} finally {
System.IntPtr unknownInterface =
Marshal.GetIUnknownForObject(netWrappedCOMObj);
while
(System.Runtime.InteropServices.Marshal.Release(unknownInterface) > 0);
while
(System.Runtime.InteropServices.Marshal.ReleaseComObject(netWrappedCOMObj)
netWrappedCOMObj = null;
GC.Collect();
GC.WaitForPendingFinalizers();

// I set a breakpoint here and I can't overwrite the COM DLL file. Why
not?
bool debug = true;
}
 
C

Carl Daniel [VC++ MVP]

Tommy Vercetti said:
I have a very simple COM object that I want to use within .NET. The COM
object was written in C++/ATL. The object works but the problem is the COM
object never seems to be released and the DLL files can never be
overwritten without restarting the computer.

Presumably stopping your .NET application will release the DLL without
rebooting...
MyLibrary.CMyCOMClass netWrappedCOMObj = new MyLibrary.CMyCOMClassClass();
try { // Currently, not using the object, just create/dispose
} finally {
System.IntPtr unknownInterface =
Marshal.GetIUnknownForObject(netWrappedCOMObj);
while (System.Runtime.InteropServices.Marshal.Release(unknownInterface) >
0);
while
(System.Runtime.InteropServices.Marshal.ReleaseComObject(netWrappedCOMObj)
netWrappedCOMObj = null;
GC.Collect();
GC.WaitForPendingFinalizers();

// I set a breakpoint here and I can't overwrite the COM DLL file. Why
not?
bool debug = true;
}

Releasing all references to an object doesn't unload the DLL. You need to
call (directly or indirectly) CoFreeUnusedLibraries() to get the DLL
unloaded. This is no different in .NET than in native COM development.

-cd
 
T

Tommy Vercetti

Presumably stopping your .NET application will release the DLL without
rebooting...
yes.

Releasing all references to an object doesn't unload the DLL. You need to
call (directly or indirectly) CoFreeUnusedLibraries() to get the DLL
unloaded. This is no different in .NET than in native COM development.

I suspected that. Thank you very much!

Do you happen to know the .NET way to invoke CoFreeUnusedLibraries()?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top