Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
This chapter is from the book

The Type Library Importer

COM components such as the Microsoft Speech API expose type information using type libraries, but .NET compilers (excluding Visual C++ .NET) don't understand type libraries. They only understand .NET metadata as a source of type information. Therefore, the key to making a COM component readily available to the .NET world is a mechanism that takes a type library and produces equivalent metadata. The Common Language Runtime's execution engine contains this functionality, which is called the type library importer.

The term type library importer was introduced previously when describing TLBIMP.EXE, but the type library importer is exposed in other ways as well. In fact, when you add a reference to a COM component in Visual Studio .NET, you are really invoking the type library importer. This creates a new assembly, and this assembly—not the type library—is what your project is really referencing. This assembly (SpeechLib.dll in the previous example) is the same file that would have been generated by TLBIMP.EXE. It's always a single file with a .dll extension, and is placed in a directory specific to your project when generated by Visual Studio .NET.

Interop Assemblies

An assembly produced by the type library importer is known as an Interop Assembly because it contains definitions of COM types that can be used from managed code via COM Interoperability. The metadata inside an Interop Assembly enables .NET compilers to resolve calls, and enables the Common Language Runtime to generate a Runtime-Callable Wrapper (RCW) at run time.

You can think of importing a type library as providing a second view of the same COM component—one for unmanaged clients and another for managed clients. This relationship is shown in Figure 3.5.

Figure 3.5 Two views of the same COM component.

The actual implementation of the COM component remains in the original COM binary file(s). In other words, nothing magical happens to transform unmanaged code into the MSIL produced by a .NET compiler. Unlike normal assemblies, which contain an abundance of both metadata and MSIL, Interop Assemblies consist mostly of metadata. The signatures have special custom attributes and pseudo-custom attributes that instruct the CLR to delegate calls to the original COM component at run time.

There are three ways of using the type library importer to create an Interop Assembly:

  • Referencing a type library in Visual Studio .NET.

  • Using TLBIMP.EXE, the command-line utility that is part of the .NET Framework SDK.

  • Using the TypeLibConverter class in the System.Runtime.InteropServices namespace.

All three of these methods produce the exact same output, although each option gives more flexibility than the previous one. TLBIMP.EXE has several options to customize the import process, but Visual Studio .NET doesn't expose these customizations when referencing a type library. Using TLBIMP.EXE to precisely mimic the behavior of Visual Studio .NET when it imports a type library, you'd need to run it as follows:

TlbImp InputFile /out:Interop.LibraryName.dll /namespace:LibraryName /sysarray

where InputFile is the file containing the type library (such as SAPI.DLL) and LibraryName is the name found inside the type library that can be viewed with OLEVIEW.EXE (such as SpeechLib). All of TLBIMP.EXE's options are covered in Appendix B, "SDK Tools Reference."

The TypeLibConverter class enables programmatic access to type library importing, and has one additional capability when compared to TLBIMP.EXE—importing an in-memory type library. The use of this class is demonstrated in Chapter 22, "Using APIs Instead of SDK Tools."

Some of the transformations made by the type library importer are non-intuitive. For example, every COM class (such as SpVoice) is converted to an interface, then an additional class with the name ClassNameClass (such as SpVoiceClass) is generated. More information about this transformation is given in the next chapter, "An In-Depth Look at Imported Assemblies," but this is why SpVoiceClass had to be used in the C++ Hello, World example. The C# and VB .NET compilers perform a little magic to enable instantiating one of these special interfaces such as SpVoice, and treats it as if you're instantiating SpVoiceClass instead.

Whereas the process of converting type library information to metadata is called importing, and the process of converting metadata to type library information is called exporting. Type library export is introduced in Chapter 8, "The Essentials for Using .NET Components from COM."

Tip

Although TLBIMP.EXE has several options that Visual Studio .NET doesn't allow you to configure within the IDE, you can reference an Interop Assembly in two steps in order to gain the desired customizations within Visual Studio .NET. First, produce the Interop Assembly exactly as you wish using TLBIMP.EXE. Then, reference this assembly within Visual Studio .NET using the .NET tab instead of the COM tab. Simply browse to the assembly and add it to your project, just as you would add any other assembly.

Everything so far assumes that a type library is available for the COM component you want to use. For several existing COM components, this is simply not the case. If the COM component has one or more IDL files, you could create a type library from them using the MIDL compiler. (Unfortunately, there's no such tool as IDLIMP that directly converts from IDL to .NET metadata.) As mentioned previously in Figure 3.5, however, .NET compilers can produce the same kind of metadata that the type library importer produces, so you can create an Interop Assembly directly from .NET source code. This advanced technique is covered in Chapter 21, "Manually Defining COM Types in Source Code." An easy solution to a lack of type information is to perform late binding, if the COM objects you wish to use support the IDispatch interface. See the "Common Interactions with COM Objects" section for more information.

Primary Interop Assemblies

The previously described process of generating Interop Assemblies has an undesirable side effect due to the differences in the definition of identity between COM and the .NET Framework. Therefore, extra support exists to map .NET and COM identities more appropriately.

In COM, a type is identified by its GUID. It doesn't matter where you get the definition; if the numeric value of the GUID is correct, then everything works. You might find a common COM interface (such as IFont) defined in ten different type libraries, rather than each library referencing the official definition in the OLE Automation type library (STDOLE2.TLB). This duplication doesn't matter in the world of COM.

On the other hand, if ten different assemblies each have a definition of IFont, these are considered ten unrelated interfaces in managed code simply because they reside in different assemblies. The containing assembly is part of a managed type's identity, so it doesn't matter if multiple interfaces have the same name or look identical in all other respects.

This is the root of the identity problem. Suppose ten software companies write .NET applications that use definitions in the OLE Automation type library (STDOLE2.TLB). Each company uses Visual Studio .NET and adds a reference to the type library, causing a new assembly to be generated called stdole.dll. Each company digitally signs the assemblies that comprise the application, including the stdole Interop Assembly, as shown in Figure 3.6.

Figure 3.6 Applications from ten different companies—each using their own Interop Assembly for the OLE Automation type library.

Now imagine a user's computer with all ten of these programs installed. One problem is that the Global Assembly Cache is cluttered with Interop Assemblies that have no differences except for the publisher's identity, shown in Figure 3.7. The difference in publishers can be seen as differences in the public key tokens.

Figure 3.7 The opposite of DLL Hell—a cluttered Global Assembly Cache with multiple Interop Assemblies for the same type library.

Even if all these Interop Assemblies aren't installed in the GAC, the computer could be cluttered in other places, such as local application directories. This is the opposite of DLL Hell—application isolation taken to an extreme. There is no sharing whatsoever, not even when it's safe for the applications to do so.

Besides clutter, the main problem is that none of these applications can easily communicate as they could if they were unmanaged COM applications. If the Payroll assembly from Figure 3.6 exposes a method with an IFont parameter and the Search assembly wants to call this, it would try passing a stdole.IFont signed by Donna's Antiques. This doesn't work because the method expects a stdole.IFont signed by Rick's Aviation. As far as the CLR is concerned, these are completely different types.

What we really want is a single managed identity for a COM component's type definitions. Such "blessed" Interop Assemblies do exist, and are known as Primary Interop Assemblies (PIAs). A Primary Interop Assembly is digitally signed by the publisher of the original COM component. In the case of the OLE Automation type library, the publisher is Microsoft. A Primary Interop Assembly is not much different from any other Interop Assembly. Besides being digitally signed by the COM component's author, it is marked with a PIA-specific custom attribute (System.Runtime.InteropServices.PrimaryInteropAssemblyAttribute), and usually registered specially.

Figure 3.8 shows what the ten applications would look like if each used the Primary Interop Assembly for the OLE Automation Type Library rather than custom Interop Assemblies.

Figure 3.8 Applications from ten different companies—each using the Primary Interop Assembly for the OLE Automation type library.

Nothing forces .NET applications to make use of a PIA when one exists. The notion of Primary Interop Assemblies is just a convention that can be used by tools, such as Visual Studio .NET, to help guide software developers in the right direction by referencing common types.

To make use of Primary Interop Assemblies, adding a reference to a type library in Visual Studio .NET is a little more complicated than what was first stated. Visual Studio .NET tries to avoid invoking the type library importer if at all possible, since it generates a new assembly with its own identity. Instead, Visual Studio .NET automatically adds a copy of a PIA to a project's references if one is registered for a type library that the user references on the COM tab of the Add Reference dialog. (A copy of an assembly is just as good as the original, since the internal assembly identity is the same.) The TLBIMP.EXE utility, on the other hand, simply warns the user when attempting to create an Interop Assembly for a type library whose PIA is registered on the current computer; it still creates a new Interop Assembly. TLBIMP.EXE does make use of registered PIAs for dependent type libraries, described in the next chapter.

As Primary Interop Assemblies are created for existing COM components, they will likely be available for download from MSDN Online or component vendor Web sites. At the time of writing, no PIAs other than the handful that ship with Visual Studio .NET exist.

Digging Deeper

It's possible to work around the identity problem caused by multiple Interop Assemblies without a notion of Primary Interop Assemblies. Due to the way in which COM interfaces are handled by the CLR, it's possible to cast from a COM interface definition in one assembly to a COM interface definition in another assembly if they have the same IID. (This does not work for regular .NET interfaces.) It's also possible to convert from a COM class defined in one assembly to a COM class defined in another assembly using the Marshal.CreateWrapperOfType method. Nothing enables converting between instances of duplicate structure definitions, but a structure's fields could be copied one-by-one.

But Primary Interop Assemblies have another important use. Interop Assemblies often need modifications, such as the ones shown in Chapter 7 to be completely usable in managed code. When you have a PIA with such customizations registered on your computer, you can benefit from these customizations simply by referencing the type library for the COM component you wish to use inside Visual Studio .NET. For example, the PIA for Microsoft ActiveX Data Objects (ADO), which ships with Visual Studio .NET, contains some customizations to handle object lifetime issues. If you created your own Interop Assembly for ADO using TLBIMP.EXE, you would not benefit from these customizations.

The process of creating and registering Primary Interop Assemblies is discussed in Chapter 15, "Creating and Deploying Useful Primary Interop Assemblies."

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020