The #import Directive
The #import directive is used to incorporate information from a type library. The content of the type library is converted into C++ classes, mostly describing the COM interfaces.
#import "filename" [attributes] #import <filename> [attributes]
- One or more #import attributes. Separate attributes with either a space or comma. For example:
#import "..\drawctl\drawctl.tlb" no_namespace, raw_interfaces_only
#import "..\drawctl\drawctl.tlb" no_namespace raw_interfaces_only
- Allows you to specify which type library you want to import. filename can be one of the following:
- A type library (.tlb or .odl). file:, which indicates type library, can precede each filename.
- The progid of a control in the type library. Note that progid: can precede each progid. For example:
For more on progids, see Specifying the Localization ID and Version Number.
- The library ID of the type library. Note that libid: can precede each library ID. For example:
#import "libid:12341234-1234-1234-1234-123412341234" version("4.0") lcid("9")
If you do not specify version or lcid, the rules that are applied to progid: are also applied to libid:.
- An executable (.exe) file.
- A library (.dll) file containing a type library resource (such as .ocx).
- A compound document holding a type library.
- Any other file format that can be understood by the LoadTypeLib API.
See the following Knowledge Base articles for more information about #import:
- Q242527 PRB: #import Wrapper Methods May Cause Access Violation
- Q269194 PRB: Compiler Errors When You Use #import with XML
filename is optionally preceded by a directory specification. The file name must name an existing file. The difference between the two syntax forms is the order in which the preprocessor searches for the type library files when the path is incompletely specified.
|Quoted form||Instructs the preprocessor to look for type library files first in the directory of the file that contains the #import statement, and then in the directories of whatever files that include (#include) that file. The preprocessor then searches along the paths shown below.|
|Angle-bracket form||Instructs the preprocessor to search for type library files along the following paths:
When you specify a progid, you can also specify the localization ID and version number of the progid. For example:
#import "progid:my.prog.id" lcid("0") version("4.0)
If you do not specify a localization ID, a progid is chosen according to the following rules:
- If there is only one localization ID, that one is used.
- If there is more than one localization ID, the first one with version number 0, 9, or 409 is used.
- If there is more than one localization ID and none of them are 0, 9, or 409, the last one is used.
- If you do not specify a version number, the most recent version is used.
#import creates two header files that reconstruct the type library contents in C++ source code. The primary header file is similar to that produced by the Microsoft Interface Definition Language (MIDL) compiler, but with additional compiler-generated code and data. The primary header file has the same base name as the type library, plus a .TLH extension. The secondary header file has the same base name as the type library, with a .TLI extension. It contains the implementations for compiler-generated member functions, and is included (#include) in the primary header file.
If importing a dispinterface property that uses byref parameters, #import will not generate __declspec(property) statement for the function.
Both header files are placed in the output directory specified by the /Fo (name object file) option. They are then read and compiled by the compiler as if the primary header file was named by a #include directive.
The following compiler optimizations come with the #import directive:
- The header file, when created, is given the same timestamp as the type library.
- When #import is processed, the compiler first checks if the header exists and is up to date. If yes, then it does not need to be re-created.
The #import directive also participates in minimal rebuild and can be placed in a precompiled header file. See Creating Precompiled Header Files for more information.
The primary type library header file consists of seven sections:
- Heading boilerplate: Consists of comments, #include statement for COMDEF.H (which defines some standard macros used in the header), and other miscellaneous setup information.
- Forward references and typedefs: Consists of structure declarations such as
struct IMyInterfaceand typedefs.
- Smart pointer declarations: The template class _com_ptr_t is a smart-pointer implementation that encapsulates interface pointers and eliminates the need to call AddRef, Release, QueryInterface functions. In addition, it hides the CoCreateInstance call in creating a new COM object. This section uses macro statement _COM_SMARTPTR_TYPEDEF to establish typedefs of COM interfaces to be template specializations of the _com_ptr_t template class. For example, for interface IMyInterface, the .TLH file will contain:
which the compiler will expand to:
typedef _com_ptr_t<_com_IIID<IMyInterface, __uuidof(IMyInterface)> > IMyInterfacePtr;
IMyInterfacePtrcan then be used in place of the raw interface pointer
IMyInterface*. Consequently, there is no need to call the various IUnknown member functions.
- Typeinfo declarations: Primarily consists of class definitions and other items exposing the individual typeinfo items returned by ITypeLib:GetTypeInfo. In this section, each typeinfo from the type library is reflected in the header in a form dependent on the TYPEKIND information.
- Optional old-style GUID definition: Contains initializations of the named GUID constants. These are names of the form CLSID_CoClass and IID_Interface, similar to those generated by the MIDL compiler.
- #include statement for the secondary type library header.
- Footer boilerplate: Currently includes
All sections, except the heading boilerplate and footer boilerplate section, are enclosed in a namespace with its name specified by the library statement in the original IDL file. You can use the names from the type library header either by an explicit qualification with the namespace name or by including the following statement:
using namespace MyLib;
immediately after the #import statement in the source code.
The namespace can be suppressed by using the no_namespace attribute of the #import directive. However, suppressing the namespace may lead to name collisions. The namespace can also be renamed by the rename_namespace attribute.
The compiler provides the full path to any type library dependency required by the type library it is currently processing. The path is written, in the form of comments, into the type library header (.TLH) that the compiler generates for each processed type library.
If a type library includes references to types defined in other type libraries, then the .TLH file will include comments of the following sort:
// // Cross-referenced type libraries: // // #import "c:\path\typelib0.tlb" //
The actual filename in the #import comment is the full path of the cross-referenced type library, as stored in the registry. If you encounter errors that are due to missing type definitions, check the comments at the head of the .TLH to see which dependent type libraries may need to be imported first. Likely errors are syntax errors (for example, C2143, C2146, C2321), C2501 (missing decl-specifiers), or C2433 ('inline' not permitted on data declaration) while compiling the .TLI file.
You must determine which of the dependency comments are not otherwise provided for by system headers and then provide an #import directive at some point before the #import directive of the dependent type library to resolve the errors.
#import can optionally include one or more attributes. These attributes tell the compiler to modify the contents of the type-library headers. A backslash (\) symbol can be used to include additional lines in a single #import statement. For example:
#import "test.lib" no_namespace \ rename("OldName", "NewName")
The #import attributes are listed below:
When importing a type library that uses one or more C++ reserved words (keywords or macros) as variable names, the auto_rename attribute renames these reserved words by appending two underscores (__) to the variable name to resolve potential name conflicts.
When a type library is referenced with #import and itself references another type library, the compiler can do an implicit #import for the other type library.
The type library is written to the .tlh file with the attribute-generated code preserved.
- First item to be excluded.
- Second item to be excluded (if necessary).
Type libraries may include definitions of items defined in system headers or other type libraries. This attribute can be used to exclude these items from the type library header files being generated. This attribute can take any number of arguments, each being a top-level type library item to be excluded.
- Prefix to be used.
By default, high-level error-handling properties and methods are exposed by member functions named without a prefix. The names are from the type library. The high_method_prefix attribute is used to specify a prefix to be used in naming these high-level properties and methods.
- Prefix to be used for the propget methods.
- Prefix to be used for the propput methods.
- Prefix to be used for the propputref methods.
By default, high-level error-handling propget, propput, and propputref methods are exposed by member functions named with prefixes Get, Put, and PutRef respectively. The high_property_prefixes attribute is used to specify alternate prefixes for all three property methods.
The implementation_only attribute suppresses the generation of the .TLH header file (the primary header file). This file contains all the declarations used to expose the type-library contents. The .TLI header file, with the implementations of the wrapper member functions, will be generated and included in the compilation.
When this attribute is specified, the content of the .TLI header is in the same namespace as the one normally used in the .TLH header. In addition, the member functions are not declared as inline.
The implementation_only attribute is intended for use in conjunction with the no_implementation attribute as a way of keeping the implementations out of the precompiled header (PCH) file. An #import statement with the no_implementation attribute is placed in the source region used to create the PCH. The resulting PCH is used by a number of source files. An #import statement with the implementation_only attribute is then used outside the PCH region. You are required to use this statement only once in one of the source files. This will generate all the required wrapper member functions without additional recompilation for each source file.
Note The implementation_only attribute in one #import statement must be use in conjunction with another #import statement, of the same type library, with the no_implementation attribute. Otherwise, compiler errors will be generated. This is because wrapper class definitions generated by the #import statement with the no_implementation attribute are required to compile the implementations generated by the implementation_only attribute.
- First item to be forcibly included.
- Second item to be forcibly included (if necessary).
Type libraries may include definitions of items defined in system headers or other type libraries. #import attempts to avoid multiple definition errors by automatically excluding such items. If items have been excluded, as indicated by warning C4192, and they should not have been, this attribute can be used to disable the automatic exclusion. This attribute can take any number of arguments, each being the name of the type-library item to be included.
- Source text to be inserted into the type library header file.
The inject_statement attribute inserts its argument as source text into the type-library header. The text is placed at the beginning of the namespace declaration that wraps the type-library contents in the header file.
The named_guids attribute tells the compiler to define and initialize GUID variables in old style, of the form LIBID_MyLib, CLSID_MyCoClass, IID_MyInterface, and DIID_MyDispInterface.
Type libraries may include definitions of items defined in system headers or other type libraries. #import attempts to avoid multiple definition errors by automatically excluding such items. When this is done, warning C4192 will be issued for each item to be excluded. You can disable this automatic exclusion by using this attribute.
The no_dual_interfaces attribute changes the way the compiler generates wrapper functions for dual interface methods. Normally, the wrapper will call the method through the virtual function table for the interface. With no_dual_interfaces, the wrapper instead calls IDispatch::Invoke to invoke the method.
The no_implementation attribute suppresses the generation of the .TLI header, which contains the implementations of the wrapper member functions. If this attribute is specified, the .TLH header, with the declarations to expose type-library items, will be generated without an #include statement to include the .TLI header file.
This attribute is used in conjunction with implementation_only.
The type-library contents in the #import header file are normally defined in a namespace. The namespace name is specified in the library statement of the original IDL file. If the no_namespace attribute is specified, then this namespace is not generated by the compiler.
If you want to use a different namespace name, use the rename_namespace attribute instead.
By default, when you use #import, you get a smart pointer declaration for all interfaces in the type library. These smart pointers are of type _com_ptr_t. The no_smart_pointers attribute suppresses the creation of these smart pointers.
The raw_dispinterfaces attribute tells the compiler to generate low-level wrapper functions for dispinterface methods and properties that call IDispatch::Invoke and return the HRESULT error code.
If this attribute is not specified, only high-level wrappers are generated, which throw C++ exceptions in case of failure.
The raw_interfaces_only attribute suppresses the generation of error-handling wrapper functions and __declspec(property) declarations that use those wrapper functions.
The raw_interfaces_only attribute also causes the default prefix used in naming the non-property functions to be removed. Normally, the prefix is raw_. If this attribute is specified, the function names are directly from the type library.
This attribute allows you to expose only the low-level contents of the type library.
- The prefix to be used.
Low-level properties and methods are exposed by member functions named with a default prefix of raw_ to avoid name collisions with the high-level error-handling member functions. The raw_method_prefix attribute is used to specify a different prefix.
Note The effects of the raw_method_prefix attribute will not be changed by the presence of the raw_interfaces_only attribute. The raw_method_prefix always takes precedence over raw_interfaces_only in specifying a prefix. If both attributes are used in the same #import statement, then the prefix specified by the raw_method_prefix attribute is used.
By default, the high-level error-handling methods use the COM support classes _bstr_t and _variant_t in place of the BSTR and VARIANT data types and raw COM interface pointers. These classes encapsulate the details of allocating and deallocating memory storage for these data types, and greatly simplify type casting and conversion operations. The raw_native_types attribute is used to disable the use of these COM support classes in the high-level wrapper functions, and force the use of low-level data types instead.
- Prefix to be used for the propget methods.
- Prefix to be used for the propput methods.
- Prefix to be used for the propputref methods.
By default, low-level propget, propput, and propputref methods are exposed by member functions named with prefixes of get_, put_, and putref_ respectively. These prefixes are compatible with the names used in the header files generated by MIDL. The raw_property_prefixes attribute is used to specify alternate prefixes for all three property methods.
- Old name in the type library.
- Name to be used instead of the old name.
The rename attribute is used to work around name collision problems. If this attribute is specified, the compiler replaces all occurrences of OldName in a type library with the user-supplied NewName in the resulting header files.
This attribute can be used when a name in the type library coincides with a macro definition in the system header files. If this situation is not resolved, then various syntax errors will be generated, such as C2059 and C2061.
Note The replacement is for a name used in the type library, not for a name used in the resulting header file.
Here is an example: Suppose a property named
MyParent exists in a type library, and a macro
GetMyParent is defined in a header file and used before #import. Since
GetMyParent is the default name of a wrapper function for the error-handling get property, a name collision will occur. To work around the problem, use the following attribute in the #import statement:
which renames the name
MyParent in the type library. An attempt to rename the
GetMyParent wrapper name will fail:
This is because the name
GetMyParent only occurs in the resulting type library header file.
- The new name of the namespace.
The rename_namespace attribute is used to rename the namespace that contains the contents of the type library. It takes a single argument, NewName, which specifies the new name for the namespace.
To remove the namespace, use the no_namespace attribute instead.
- The new name of the namespace.
- The number of the type library in filename.
If multiple type libraries are built into a single DLL, it possible to load libraries other than the primary by using tlbid. For example:
#import <MyResource.dll> tlbid(2)
is equivalent to:
END C++ Specific