Table Of Content.NET and COM: The Complete
Interoperability Guide
Adam Nathan
800 East 96th Street,Indianapolis,Indiana,46240 USA
.NET and COM: The Complete EXECUTIVEEDITOR
Shelley Kronzek
Interoperability Guide
Copyright © 2002 by Sams Publishing DEVELOPMENTEDITOR
Anne Marie Walker
All rights reserved. No part of this book shall be reproduced,stored in a
retrieval system,or transmitted by any means,electronic,mechanical,photo- MANAGINGEDITOR
copying,recording,or otherwise,without written permission from the pub- Matt Purcell
lisher. No patent liability is assumed with respect to the use of the information
PROJECTEDITOR
contained herein. Although every precaution has been taken in the preparation
Andy Beaster
of this book,the publisher and author assume no responsibility for errors or
omissions. Nor is any liability assumed for damages resulting from the use of COPYEDITORS
the information contained herein. Ned Snell
Katie Robinson
International Standard Book Number:0-672-32170-x
Library of Congress Catalog Card Number:2001093566 INDEXER
Ginny Bess
Printed in the United States of America
PROOFREADERS
First Printing:January 2002
Kay Hoskin
04 03 02 01 4 3 2 1 Plan-It Publishing
Trademarks TECHNICALEDITORS
All terms mentioned in this book that are known to be trademarks or service Dave Mortenson
Bob Willer
marks have been appropriately capitalized. Sams Publishing cannot attest to
the accuracy of this information. Use of a term in this book should not be TEAMCOORDINATOR
regarded as affecting the validity of any trademark or service mark. Pamalee Nelson
Warning and Disclaimer INTERIORDESIGNER
Anne Jones
Every effort has been made to make this book as complete and as accurate as
possible,but no warranty or fitness is implied. The information provided is on COVERDESIGNER
Aren Howell
an “as is”basis. The author and the publisher shall have neither liability nor
responsibility to any person or entity with respect to any loss or damages aris- PAGELAYOUT
ing from the information contained in this book. Susan Geiselman
Rebecca Harmon
CherylLynch
Michelle Mitchell
PART I Background
1 Introduction to the .NET Framework 13
What Is .NET? ......................................................................................14
The .NET Framework ......................................................................15
Features of the .NET Framework ........................................................16
Version Resiliency (The End of DLL Hell) ....................................16
Trivial Deployment ..........................................................................19
Fine-Grained Security ....................................................................20
Platform Neutrality ..........................................................................21
Concepts Important for This Book ......................................................22
Assemblies ......................................................................................22
Metadata ..........................................................................................26
Reflection ........................................................................................26
Custom Attributes ............................................................................28
Languages and Tools ............................................................................33
C# ....................................................................................................34
Visual Basic .NET ..........................................................................38
C++ ..................................................................................................42
IL Assembler (ILASM) ..................................................................45
IL Disassembler (ILDASM) ............................................................45
Conclusion ............................................................................................46
2 Bridging the Two Worlds—Managed and Unmanaged Code 47
Managed Code Versus Unmanaged Code ............................................48
Goals of Unmanaged Code Interaction ..........................................48
How Can Using Unmanaged Code Be Secure? ..............................49
How Unmanaged Code Interacts with Managed Code ........................49
Platform Invocation Services (PInvoke) ..........................................49
Mixed-Mode Programming Using Managed
Extensions to C++ ........................................................................50
Java User Migration Path to .NET (JUMP to .NET) ......................51
COM Interoperability ......................................................................51
Unmanaged Code Isn’t Always the Answer ........................................72
Conclusion ............................................................................................72
.NETANDCOM: THECOMPLETEINTEROPERABILITYGUIDE
Part II Using COMComponents in .NETApplications
3 The Essentials for Using COM in Managed Code 77
Referencing a COM Component in Visual Studio .NET ....................78
Referencing a COM Component Using Only the .NET
Framework SDK ................................................................................81
Example:A Spoken Hello, WorldUsing the Microsoft
Speech API ........................................................................................83
The Type Library Importer ..................................................................84
Interop Assemblies ..........................................................................84
Primary Interop Assemblies ............................................................86
Using COM Objects in ASP.NET Pages ..............................................90
Example:Using ADO in ASP.NET ................................................92
Using COM+ Components ..............................................................96
An Introduction to Interop Marshaling ................................................96
Common Interactions with COM Objects ............................................99
Creating an Instance ........................................................................99
Calling Methods and Properties on a COM Object ......................101
Releasing a COM Object ..............................................................109
Casting to an Interface (QueryInterface) ................................110
Error Handling ..............................................................................112
Enumerating Over a Collection ....................................................114
Passing the Right Type of Object................................................115
Late Binding and By-Reference Parameters ................................119
Using ActiveX Controls in .NET Applications ..................................120
Referencing an ActiveX Control in Visual Studio .NET ..............121
Referencing an ActiveX Control Using Only the .NET
Framework SDK ........................................................................122
Example:A Simple Web Browser ................................................123
Deploying a .NET Application That Uses COM ................................126
Example:Using Microsoft Word to Check Spelling ..........................127
Conclusion ..........................................................................................137
4 An In-Depth Look at Imported Assemblies 139
Converting the Library ........................................................................141
Converting COM Data Types ............................................................143
Combining Several Types in One ..................................................145
Complex Types ..............................................................................152
Converting Methods and Properties ..................................................162
Methods ........................................................................................162
Properties ......................................................................................171
Special DISPIDs ............................................................................173
CONTENTS
Converting Interfaces ..........................................................................177
Converting Classes ..............................................................................179
Coclass Interfaces and Parameter/Field Replacement ..................180
The RCW Class ............................................................................182
Converting Modules ............................................................................187
Converting Structures ........................................................................189
Converting Unions ..............................................................................191
Converting Enumerations ..................................................................193
Converting Typedefs ..........................................................................194
Converting ActiveX Controls ............................................................196
Conclusion ..........................................................................................199
5 Responding to COM Events 201
Callbacks in .NET ..............................................................................202
Callback Interfaces ........................................................................202
Delegates ......................................................................................204
Events ............................................................................................208
Callbacks in COM ..............................................................................214
Handling COM Events in Managed Code ..........................................218
The Raw Approach ........................................................................218
Type Library Importer Transformations ........................................222
Using the Event Abstraction ..........................................................224
Lazy Connection Point Initialization ............................................227
Connectable Objects You Don’t Instantiate ..................................229
Handling ActiveX Control Events in Managed Code ........................235
ActiveX Importer Transformations ..............................................235
Using ActiveX Events ..................................................................240
Conclusion ..........................................................................................245
6 Advanced Topics for Using COM Components 247
Do-It-Yourself Marshaling ..................................................................248
C# Unsafe Code Versus System.Runtime.InteropServicesAPIs ..250
Examples of Manipulating IntPtrTypes ....................................258
Threading and Apartments ..................................................................275
Threading in COM Versus Threading in .NET ............................275
Choosing Your Apartment State in a .NET Application ..............277
Callbacks from a COM Object to a .NET Object ........................282
Troubleshooting an InvalidCastException ......................................289
QueryInterfaceFailure ................................................................290
Casting to an RCW Class ..............................................................295
Garbage Collection ............................................................................299
Securing Unmanaged Calls ................................................................304
Using COM+ and DCOM Objects ....................................................309
.NETANDCOM: THECOMPLETEINTEROPERABILITYGUIDE
Inheriting from COM Classes ............................................................311
Debugging into COM Components ....................................................315
Monitoring Performance ....................................................................320
Conclusion ..........................................................................................321
7 Modifying Interop Assemblies 323
How to Change an Assembly’s Contents ..........................................325
IL Assembler Syntax ..........................................................................328
Data Types ....................................................................................332
Passing Parameters ........................................................................334
MarshalAsAttributeSyntax ........................................................334
Changing Data Types ..........................................................................340
Exposing Success HRESULTs ................................................................342
Arrays ..................................................................................................348
ExposingSAFEARRAYs Differently ..................................................348
Adding Size Information to C-Style Arrays ..................................349
Custom Attributes ..............................................................................351
Changing Attribute Contents ........................................................354
Marking Classes as Visual Basic Modules ....................................356
Adding Back helpstringInformation ..........................................358
Adding Custom Marshalers ..........................................................364
Adding DISPIDs ............................................................................366
Adding Back IDL Custom Attributes ............................................371
Adding Methods to Modules ..............................................................372
Conclusion ..........................................................................................374
Part III Using .NETComponents in COMApplications
8 The Essentials for Using .NET Components from COM 379
A Sample .NET Component ..............................................................380
Using a .NET Component in Visual Basic 6 ......................................382
Using a .NET Component in Unmanaged Visual C++ ......................385
Using a .NET Component in Unmanaged JScript ............................388
Assembly Registration ........................................................................390
The Type Library Exporter ................................................................394
.NET Class Interfaces ........................................................................397
Interacting with a .NET Object ..........................................................399
Creating a .NET Object ................................................................399
Calling Members on a .NET Object ............................................400
Getting Rich Error Information ....................................................403
Enumerating Over a Collection ....................................................415
Deploying a COM Application That Uses .NET ................................415
Hosting Windows Forms Controls in Internet Explorer ....................417
Conclusion ..........................................................................................422
CONTENTS
9 An In-Depth Look at Exported Type Libraries 425
Converting the Assembly ....................................................................426
Converting .NET Data Types ..............................................................429
Converting Members ..........................................................................434
Methods ........................................................................................434
Properties ......................................................................................441
Fields ............................................................................................444
Events ............................................................................................446
Converting Interfaces ..........................................................................447
Converting Classes ..............................................................................449
Converting Value Types ......................................................................452
Converting Enumerations ..................................................................453
Conclusion ..........................................................................................457
10 Advanced Topics for Using .NET Components 459
Avoiding Registration ........................................................................460
Hosting the Common Language Runtime ....................................460
Using the ClrCreateManagedInstanceAPI ............................468
Hosting Windows Forms Controls in Any
ActiveX Container ..........................................................................471
Working Around COM-Invisibility ....................................................477
Using Reflection to Invoke Static Members ......................................482
Handling .NET Events ........................................................................488
Unexpected Casing in Type Libraries ................................................489
Advanced Shutdown Topics ..............................................................492
Conclusion ..........................................................................................493
Part IV Designing Great .NETComponents for COMClients
11 .NET Design Guidelines for Components Used by
COM Clients 497
Naming Guidelines ............................................................................499
Names to Avoid ............................................................................500
Namespaces and Assembly Names ..............................................502
Case Insensitivity ..........................................................................503
Usage Guidelines ................................................................................506
Interfaces Versus Classes ..............................................................506
Interfaces Versus Custom Attributes ............................................508
Properties Versus Fields ................................................................510
Using Overloaded Methods ..........................................................511
Using Constructors ........................................................................513
Using Enumerations ......................................................................514
Choosing the Right Data Types ....................................................516
.NETANDCOM: THECOMPLETEINTEROPERABILITYGUIDE
Reporting Errors ................................................................................520
Defining New Exception Types ....................................................520
General Guidelines ........................................................................523
Exposing Enumerators to COM ........................................................524
Versioning ..........................................................................................527
Library Identifiers (LIBIDs) ..........................................................529
Class Identifiers (CLSIDs) ............................................................530
Interface Identifiers (IIDs) ............................................................531
Deployment ........................................................................................532
Testing Your Component from COM ................................................535
Conclusion ..........................................................................................537
12 Customizing COM’s View of .NET Components 539
Customizing Data Types ....................................................................540
MarshalAsAttributeBasics ....................................................541
Customizing Arrays ......................................................................549
Detecting Incorrect Use of MarshalAsAttribute ....................552
Customizing Data Flow ................................................................553
Customizing Structure Layout ............................................................554
Exposing Class Interfaces ..................................................................556
Using Visual Basic .NET’s ComClassAttribute............................560
Making APIs Invisible to COM ..........................................................562
Customizing Registration ..................................................................565
Choosing Your Own ProgID ........................................................566
Adding Arbitrary Registration Code ............................................567
Providing Your Own GUIDs ..............................................................574
Providing Your Own DISPIDs ............................................................574
Controlling Interface Derivation ........................................................578
Returning a Specific HRESULT ..........................................................579
Disabling Type Library Marshaling of .NET Interfaces ....................580
Creating Multi-Cultured Methods ......................................................582
Using Optional Parameters in Any Language ....................................583
Exposing .NET Objects As COM+ Objects ......................................584
Conclusion ..........................................................................................586
13 Exposing .NETEvents to COM Clients 591
Exposing Events Without Using Extra CLR Support ........................592
Exposing Events Using Extra CLR Support ......................................598
UsingComSourceInterfacesAttribute ................................598
Defining a Source Interface ..........................................................600
ThePhoneExample Revisited ......................................................602
Visual Basic .NET’s ComClassAttribute ................................605
Design Guidelines ........................................................................608
CONTENTS
Example:Handling a .NET Windows Form’s Events from COM ....611
The .NET Event Source ................................................................611
The COM Event Sink ....................................................................623
Conclusion ..........................................................................................626
14 Implementing COM Interfaces for Binary Compatibility 627
Getting Interface Definitions ..............................................................628
Binary Compatibility with Visual Basic 6 Classes ............................629
Example:Implementing Office XP Smart Tag Interfaces ..................634
Running the Example Using Visual Studio .NET ........................646
Running the Example Using Only the .NET
Framework SDK ........................................................................650
Interface Implementation Shortcuts in Visual Studio .NET ..............650
Common Problems When Implementing COM Interfaces ................653
Parameterized Properties ..............................................................653
Interface Inheritance ......................................................................654
Returning Specific HRESULTs ......................................................656
COM Interfaces with Default CCW Implementations ......................657
IUnknown ......................................................................................657
IDispatch ....................................................................................659
IMarshal ......................................................................................672
IProvideClassInfo ..................................................................673
ISupportErrorInfo ..................................................................674
IConnectionPointContainer..................................................675
IObjectSafety ..........................................................................676
COM Interfaces Bridged to Different .NET Types ............................678
Conclusion ..........................................................................................679
Part V Designing Great COMComponents for .NETClients
15 Creating and Deploying Useful Primary Interop Assemblies 683
Primary Interop Assembly or Brand New Assembly? ......................684
Creating a Primary Interop Assembly ................................................686
Generating a Strong Name ............................................................686
Handling References to Other Type Libraries ..............................687
Naming the Output Assembly ......................................................690
Customizing the Metadata ............................................................693
Deploying and Registering a Primary Interop Assembly ..................694
Writing IDL That Produces Good Type Libraries ..............................697
Referencing External Types ..........................................................698
Defining Classes ............................................................................702
Defining Structures,Enums,and Unions ......................................707
Using Constants Appropriately ....................................................709
.NETANDCOM: THECOMPLETEINTEROPERABILITYGUIDE
Avoiding Ignored Constructs ........................................................710
Registering the Type Library ........................................................711
What About ActiveX Controls? ..........................................................712
Conclusion ..........................................................................................713
16 COM Design Guidelines for Components Used by
.NET Clients 715
General Guidelines ............................................................................716
Using Array Parameters ......................................................................717
UseSAFEARRAYs ..........................................................................717
Use Zero Lower Bounds ..............................................................719
Use Single-Dimensional Arrays ....................................................719
Issues with VARIANTParameters ........................................................720
Reporting Errors ................................................................................720
Reserve Failure HRESULTs for Exceptional Circumstances ..........721
Don’t Return Success HRESULTs Other than S_OK ......................721
Set Additional Error Information ..................................................722
Adjusting Certain COM-Specific Idioms ..........................................729
Passing a Pointer to Anything ......................................................729
Passing Type Information ..............................................................730
Passing Error Information ............................................................731
Managing Limited Resources ............................................................731
Threading and Apartment Guidelines ................................................733
Providing Self-Describing Type Information ....................................734
Naming Guidelines ............................................................................734
Performance Considerations ..............................................................735
Conclusion ..........................................................................................738
17 Implementing .NET Interfaces for Type Compatibility 739
Class Interfaces ..................................................................................741
Interface Inheritance ..........................................................................743
Considerations for Visual C++ Programmers ....................................747
Example:Implementing IDisposableto Clean Up Resources ....750
Considerations for Visual Basic 6 Programmers ................................759
Example:Implementing IFormattableto Customize ToString ..761
Example:Implementing IHashCodeProviderandIComparer
to Use a COM Object as a Hashtable Key ................................764
Conclusion ..........................................................................................767
Part VI Platform Invocation Services (PInvoke)
18 The Essentials of PInvoke 771
Using PInvoke in Visual Basic .NET ..................................................773
Using PInvoke in Other .NET Languages ..........................................776