Tuesday, April 10, 2007

Using .NET objects via COM, part 2

As an addendum to my previous post, I just struggled through troubleshooting a couple of problems with using the .NET COM interop with regasm.

All members of your exposed classes must only reference other exposed classes. For instance, I added an internal class to my assembly and then created a field that stored an instance of it in my public object that was to be exposed during COM. This resulted in another obscure error code in Server.CreateObject: 8013150a.

Note that this only applies to instances of classes exposed through properties or fields in your exposed object, even if those fields/properties are private, protected, or internal. Objects instantiated inside methods and stored as local variables do not appear to cause any problems.

Debug.WriteLine will cause NullReferenceException to be thrown when a debugger is not attached. This one drove me nuts for a while; I kept getting a NullReferenceException in an odd place that didn't make any sense when I tried to call one of my methods from COM (it worked just fine calling it from .NET). I attached WinDbg to the w3wp.exe process to trace what was going on, and suddenly it stopped throwing the NullReferenceException. I unattached the debugger, and it came right back!

I pondered a moment what difference the debugger would be making, and on a whim I went through my object and removed any references to the Debug class. Apparently that did the trick, as now I have no more problems with a mysterious NullReferenceException being thrown.

No comments: