Exposing COM to .NET Compact Framework Components
Starting with the .NET Compact Framework version 2.0, you can call COM objects from managed code. You can also import a type library with theprovided by the full .NET Framework, or in Visual Studio you can add a type library reference to your project. An imported type library is also known as an interop assembly because it contains definitions of COM types described in metadata.
If memory in native code that was originally allocated in managed code remains stored by a native code library after the native function call returns, the native library object must be pinned in managed code so the garbage collector does not move or collect it. You can use thestructure to pin the object.
Managed code must be responsible for aligning data types according to the proper byte boundaries, known as the packing process, specified for the native operating system.
There are three tasks for calling COM objects from the .NET Compact Framework:
Create managed definitions of your COM interfaces and types.
Reference those definitions from your project.
Use your COM interfaces and types as managed types.
You can also "hand code" managed definitions.
Referencing Interop Assemblies
Interop assemblies are imported type libraries that contain definitions of COM types described in metadata generated by the Type Library Importer or Visual Studio.
To reference the interop assembly when building projects, use the /r: switch with command-line compilers. This is done for you when you add a reference to a type library in Visual Studio.
Using COM Types As Managed Types
Members of the default interface are added to the class during import. The IDispatch vs. IUnknown call, QueryInterface, and COM reference counting are handled automatically. Failure HRESULT values are automatically mapped to exceptions.
After you import a COM type, you can use it as any other managed type in programming tasks such as the following:
Create instances with the new keyword (New in Visual Basic).
Call directly through the class.
Avoid choosing between IDispatch vs. IUnknown-style calls.
Cast to specific interfaces as necessary.