The #import Directive

C++ Specific

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.

Syntax

#import "filename" [attributes]

#import <filename> [attributes]

attributes:

attribute1, attribute2, ...

attribute1 attribute2 ...

filename is the name of the file containing the type library information. A file can be one of the following types:

The filename is optionally preceded by a directory specification. The filename must name an existing file. The difference between the two forms is the order in which the preprocessor searches for the type library files when the path is incompletely specified.

Syntax Form Action
Quoted form This form instructs the preprocessor to first look for type library files in the same 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 This form instructs the preprocessor to search for type library files along the paths shown below.

The compiler will search in the following directories for the named file:

  1. the PATH environment variable path list

  2. the LIB environment variable path list

  3. the path specified by the /I (additional include directories) compiler option

#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:

exclude high_method_prefix
high_property_prefixes implementation_only
include(…) inject_statement
named_guids no_auto_exclude
no_implementation no_namespace
raw_dispinterfaces raw_interfaces_only
raw_method_prefix raw_native_types
raw_property_prefixes rename
rename_namespace  

#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.

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 #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

The primary type library header file consists of seven sections:

  1. Heading boilerplate:   Consists of comments, #include statement for COMDEF.H (which defines some standard macros used in the header), and other miscellaneous setup information.

  2. Forward references and typedefs:   Consists of structure declarations such as struct IMyInterface, and typedefs for any TKIND_ALIAS items.

  3. 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 IFoo, the .TLH file will contain:

    _COM_SMARTPTR_TYPEDEF(IFoo, __uuidof(IFoo));

    which the compiler will expand to:

    typedef _com_ptr_t<_com_IIID<IFoo, __uuidof(IFoo)> > IFooPtr;

    Type IFooPtr can then be used in place of the raw interface pointer IFoo*. Consequently, there is no need to call the various IUnknown member functions.

  4. 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.

  5. 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.

  6. #include statement for the secondary type library header.

  7. Footer boilerplate:   Currently includes #pragma pack(pop).

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 (e.g. 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 in order to resolve the errors.

The exclude attribute

exclude("Name1"[, "Name2",...])

Name1

First item to be excluded

Name2

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.

The high_method_prefix attribute

high_method_prefix("Prefix")

Prefix

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.

The high_property_prefixes attribute

high_property_prefixes("GetPrefix","PutPrefix","PutRefPrefix")

GetPrefix

Prefix to be used for the propget methods

PutPrefix

Prefix to be used for the propput methods

PutRefPrefix

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

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.

The include(...) attribute

include(Name1[, Name2, ...])

Name1

First item to be forcibly included

Name2

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.

The inject_statement attribute

inject_statement("source_text")

source_text

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

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.

The no_implementation attribute

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 no_auto_exclude attribute

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_namespace attribute

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, this namespace is not generated by the compiler.

If you want to use a different namespace name, use the rename_namespace attribute instead.

The raw_dispinterfaces attribute

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

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 raw_method_prefix attribute

raw_method_prefix("Prefix")

Prefix

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.

The raw_native_types attribute

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.

The raw_property_prefixes attribute

raw_property_prefixes("GetPrefix","PutPrefix","PutRefPrefix")

GetPrefix

Prefix to be used for the propget methods

PutPrefix

Prefix to be used for the propput methods

PutRefPrefix

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.

The rename attribute

rename("OldName","NewName")

OldName

Old name in the type library

NewName

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:

rename(“MyParent”,”MyParentX”)

which renames the name MyParent in the type library. An attempt to rename the GetMyParent wrapper name will fail:

rename(“GetMyParent”,”GetMyParentX”)

This is because the name GetMyParent only occurs in the resulting type library header file.

The rename_namespace attribute

rename_namespace("NewName")

NewName

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.

END C++ Specific