by skeet via Jon Skeet: Coding Blog on 7/7/2009 10:28:46 PM
C# 4 has some great features to make programming against COM components bearable fun and exciting. In particular:
I'm currently writing about these features for the book (don't forget to buy it cheap on Friday) but I'm not really a COM person. I want to be able to see these compiler features at work against a really simple type. Unfortunately, these really are COM-specific features... so we're going to have to persuade COM that the type really is a COM type.
I got slightly stuck on this first, but thanks to the power of Stack Overflow, I now have a reasonably complete demo "fake" COM type. It doesn't do a lot, and in particular it doesn't have any events, but it's enough to show the compiler features:
We have an interface representing our COM type, and a class which the interface claims will implement it. Fortunately the compiler doesn't actually check that, so we can get away with leaving it entirely unimplemented. It's also worth noting that our optional parameters can be by-reference parameters (which you can't normally do in C# 4) and we haven't given them any default values (as those are ignored for COM anyway).
This is compiled just like any other assembly:
Then we get to use it with a test program:
This is compiled either in the old "deploy the PIA as well" way (after adding a cast in the last line):
... or by linking the PIA instead:
(The difference is just using /l instead of /r.)
/l
/r
When the test code is compiled as a reference, it decompiles in Reflector to this (I've added whitespace for clarity):
Note how the compiler has created local variables to pass by reference; any changes to the parameter are ignored when the method returns. (If you actually pass a variable by reference, the compiler won't take that away, however.)
When the code is linked instead, the middle section is the same, but the construction and the line calling MakeMeDynamic are very different:
MakeMeDynamic
The interface is embedded in the generated assembly, but with a slightly different set of attributes:
The class isn't present at all.
I should point out that doing this has no practical benefit in real code - but the ability to mess around with a pseudo-COM type rather than having to find a real one with the exact members I want will make it a lot easier to try a few corner cases for the book.
So, not a terribly productive evening in terms of getting actual writing done, but interesting nonetheless...
Original Post: Faking COM to fool the C# compiler
The content of the postings is owned by the respective author. CSharpFeeds is not responsible for the contents of the postings. This site is automatically generated and cannot be reviewed for abusive content. If you find abusive content on CSharpFeeds, please contact us. Designated trademarks and brands are the property of their respective owners. All rights reserved.