Using Attributes in C Code

team lib

Using Attributes in C++ Code

In case you havent used attributes in C++ code in Visual Studio .NET, this section briefly explains attribute syntax and usage. The basic syntax will be familiar to anyone who has done IDL coding.

Attributes can be attached to elements in C++ code by placing square brackets immediately before the element that the attributes apply to:

 [coclass,uuid(12EA4458-7753-11D2-098A-00C04F37BBFF)] classMyObject { ... }; 

In the example, the coclass and uuid attributes are being applied to the class that follows . If you need to specify more than one attribute, use a comma- separated list. Attributes can take parametersin the example, coclass doesnt take any parameters, while uuid takes one, a GUID.

Attribute parameters can be mandatory or optional. Mandatory parameters (also called positional parameters ) occur first in the argument list. Optional (or named ) parameters occur after any positional ones, and they use a name =value syntax to denote which optional parameters are being specified. This means it doesnt matter in which order named parameters are specified. Heres an example:

 [module(dll,uuid="{1D196988-3060-486E-A4AC-38F9685D3BF7}", name="SimpleObject", helpstring="SimpleObject1.0TypeLibrary", resource_name="IDR_SIMPLEOBJECT")]; 

The module attribute has one positional parameter ( dll ) and four named parameters. The named parameters can be specified in any order.


Although it has no bearing on how you use attributes in your C++ code, what youre doing when you specify an attribute is coding a constructor call. Attributes are implemented by classes, and when you attach an attribute to a code element, youre specifying how the attribute object should be created by giving the parameters for the constructor. The attribute object can then be invoked by the compiler or run time to do its job.

As well as using COM attributes, you can also write your own custom attributes for use with C++ classes and members . These have nothing to do with COM and are not used by the compiler. Instead, theyre used to provide extra run-time information about types, which can be retrieved using the .NET Framework reflection mechanism. For example, you could create a custom attribute that holds information about the revision history of a class. Writing custom attributes is outside the scope of this book; if you want to know more, read Programming with Managed Extensions for Microsoft Visual C++ .NET by Richard Grimes, published by Microsoft Press.

team lib

COM Programming with Microsoft .NET
COM Programming with Microsoft .NET
ISBN: 0735618755
EAN: 2147483647
Year: 2006
Pages: 140

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: