This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com PUBLISHED BY Microsoft Press A Division of Microsoft Corporation One Microsoft Way Redmond, Washington 98052-6399 Copyright © 2003 by Richard Grimes All rights reserved No part of the contents of this book may be reproduced or trans any means without the written permission of the publisher Library of Congress Cataloging-in-Publication Data Grimes, Richard, 1964Programming with Managed Extensions for Microsoft Visual C++ NET / Richard Grim p cm Includes index ISBN 0-7356-1724-4 Microsoft Visual C++ C++ (Computer program language) Microsoft NET I Title QA76.73.C153 G7428 2002 005.26'8 dc21 2002071751 Printed and bound in the United States of America QWE Distributed in Canada by H.B Fenn and Company Ltd A CIP catalogue record for this book is available from the British Library Microsoft Press books are available through booksellers and distributors worldwide about international editions, contact your local Microsoft Corporation office or contac International directly at fax (425) 936-7329 Visit our Web site at www.microsoft.co comments to mspinput@microsoft.com ActiveX, DirectX, IntelliSense, Microsoft, Microsoft Press, MS-DOS, MSDN, Visual Ba Visual SourceSafe, Visual Studio, Win32, Windows, and Windows NT are either trademarks of Microsoft Corporation in the United States and/or other countries Ot company names mentioned herein may be the trademarks of their respective owner The example companies, organizations, products, domain names, e-mail addresses, places, and events depicted herein are fictitious No association with any real compa product, domain name, e-mail address, logo, person, place, or event is intended or This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com product, domain name, e-mail address, logo, person, place, or event is intended or Acquisitions Editor: Danielle Bird Project Editor: Sally Stickney Technical Editor: Jim Fuchs Body Part No X08-81826 This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Acknowledgments As with any technical book, there are many people who have contributed to this book other than those beneath the byline First I have to mention Danielle Bird, acquisitions editor at Microsoft Press, who helped to get this book started and smoothed its development The ink would never have found its way to the paper without the steady hand of project editor, Sally Stickney, or without my copy editor, Holly Viola, who ensured that my English became an English that you could read and understand On the technical side, I am indebted to Jim Fuchs, my technical editor at Microsoft Press, and to Christophe Nasarre, for reviewing the manuscript and pointing out when my code would fail to compile or produce results that I did not expect I am also grateful to Ronald Laermans, Mike Hall, and Jeff Peil from the Visual C++ team at Microsoft for answering my questions about the C++ compiler Finally, no book would issue from my PC without my wife Ellinor provides love, support, and copious quantities of tea while I write Richard Grimes Kenilworth, United Kingdom June 2002 This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Introduction The most immediately obvious feature of NET is the runtime, which Microsoft calls the common language runtime The concept of a runtime is not new to Microsoft technologies— Visual Basic applications have always carried around the baggage of the Visual Basic runtime, and Microsoft’s foray into Java brought about the Microsoft Java Virtual Machine (JVM) But unlike the Visual Basic runtime and the JVM, the NET runtime is not constrained to a specific language Both Microsoft and third-party companies have produced several languages that can produce code to run under the NET runtime Some, such as C#, are new languages, and others use the syntax of existing languages Microsoft Visual C++ NET is an existing language that has been extended to produce NET code, and these extensions are called the Managed Extensions for C++ The Managed Extensions allow C++ classes to take advantage of NET garbage collection and memory protection More important, they enable C++ code to access the NET Framework class library and libraries written by any of the other NET-enabled languages; and other languages can use managed libraries written in C++ No longer C++ developers need to use myriad technologies such as COM, DLL exported functions, and template libraries to get access to the libraries they need to create a fully featured application; just about all the necessary library code is available as NET classes in the NET Framework class library The Managed Extensions essentially define a subset of the C++ language—it looks like C++, and it smells like C++, but it is really NET You might be asking yourself, “If NET allows me to choose between a multitude of languages, why should I use C++ to write my NET code?” C++ has always been a systems language, and it gives you the power and flexibility to produce truly innovative solutions This ethos has been carried over to the Managed Extensions, in which you have not only the complete features of the NET runtime and class library but also the full power of the unmanaged language Indeed, C++ is the only language in which you can mix NET code and unmanaged code in the same source file The compiler also allows you to seamlessly access all your unmanaged libraries: static-link libraries, template libraries, COM objects, and DLLs This easy access means that you can reuse all your existing code and, in the few cases in which the NET Framework class library does not have suitable classes, use existing unmanaged libraries Again, no other language gives you these facilities, so no other language can be regarded as the NET systems language This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com The Contents of This Book This book is organized to take you end-to-end through the development process I start by describing the basic features of the language, and then I progress through NET features such as interop, delegates, and GUI applications The last two chapters of the book focus on the project management and debugging features, respectively, of Visual Studio NET You not need Visual Studio NET to develop NET code in C++, but as you’ll see from Chapter and Chapter 7, your work will be far easier if you use it A more detailed description of the contents of each chapter follows Chapter In this first chapter, I cover the basic features of the Managed Extensions I start by explaining how to develop managed types and how these differ from unmanaged types, both in their declaration and their use I cover how to use managed arrays, interfaces, and exceptions C++ written with the Managed Extensions follows the NET model rather than the C++ model in terms of inheritance and casts, so I conclude this chapter by describing how NET differs from unmanaged C++ in these respects Chapter One of the reasons for using C++ is that it allows you to use existing unmanaged code in your NET projects The Managed Extensions compiler has a technology quaintly called It Just Works! (IJW) This technology allows you to use unmanaged libraries in managed projects and to intermingle managed and unmanaged classes In this chapter, I tell you how to use IJW and give some insights into how it works .NET also has an attribute-based technology called platform invoke that allows any NETenabled language to access code exported from a DLL I explain how you can use platform invoke and describe how you can customize the marshaling it performs A variation of platform invoke is COM interop, which is the final subject of this chapter COM interop allows managed code to use COM objects as if they were NET objects, and it allows unmanaged code to use NET objects as if they were COM objects I go over how COM interop works and how you can register classes and generate the attributes required by COM interop Chapter Function pointers are useful in unmanaged projects because they allow function binding to be performed at run time rather than at compile time C++ virtual functions and COM interfaces are based on function pointers, and function pointers also enable you to define notification systems .NET has its own version of function pointers—called delegates—that are type-safe, eliminating one big disadvantage of unmanaged function pointers: namely, casting between function pointer types This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com In this chapter, I show you how to use delegates with C++, how this approach compares with unmanaged function pointers, and how you can use delegates with unmanaged code I also explain how to make asynchronous calls through delegates (using a system-provided thread) and talk about how to write multithreaded code with NET Finally, I clarify how NET uses delegates to implement a formal notification mechanism called NET events Chapter The NET Framework augments Windows with a new graphics library called GDI+ This is an unmanaged library, but the NET Framework comes with NET wrapper classes The windowing technology in NET is called Windows Forms You can draw on a form with GDI+, and you can use a form as a container for controls In this chapter, I explain how you can create GUI applications in C++ with Windows Forms and describe how to implement such applications using Win32 windows I also show how to handle Windows messages through NET events and how to bypass this mechanism to get the most control over a window’s behavior I also go over how to use managed resources and native resources efficiently in a managed class so that resources are released when your application no longer needs them Finally, I define “managed” resources and explain how to add a managed resource to your application, and discuss how to localize resources Chapter In this chapter, I delineate how NET code is stored in executable files I start by explaining the format of NET assemblies and describing how they are implemented as Win32 portable executable (PE) files I then discuss how you can get information about NET metadata and code within an assembly by using COM objects the NET Framework supplies The NET runtime is implemented with unmanaged code, and Microsoft has designed the runtime so that unmanaged code can get access to the runtime through COM objects In this chapter, I explain how to use these objects to access and configure the runtime from unmanaged code and how to instruct the runtime to run managed code A managed application can be configured through an XML file associated with the application The runtime reads the configuration file when the application starts so that it can get information about the facilities that the application requires One of the big advantages of the runtime is that it will load only the libraries that your application was specifically built to use You can configure the rules that the runtime uses to locate those libraries via the configuration file Your code can also access the information in a configuration file, and in this chapter, I show you how to this and how to extend configuration files and the API to read them Finally, I describe code access security and demonstrate how to use it in your code I also show the default permissions that are required by NET code written with Managed Extensions for C++ Chapter This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Visual Studio NET is a mixed managed and unmanaged application that integrates various application-development tools In this chapter, I explain how you can use the environment to develop your projects I cover the facilities of the editor and the tools that are provided to allow you to manage your projects I talk about the Visual Studio NET project wizards and the types of C++ projects that you can develop I conclude the chapter with examples of the types of managed projects that you can develop and describe how to customize the code provided by the project wizard Chapter The last stage of your development cycle is typically the testing stage: you need to test the project to ensure that it works the way you intend it to, and when it does not work as expected, you will need to debug the code to determine where the problem lies Although the testing stage often comes at the end of a development cycle, you can save yourself a lot of effort by writing code up front that provides diagnostic information In this chapter, I describe the facilities that the NET Framework offers to allow you to diagnose problems in your code and explain how you can collect this diagnostic information Visual Studio NET has an integrated managed and native code debugger, so once you have identified a problem you can step through your code to pinpoint the source I explain how to use the debugger and its various facilities I also talk about the special issues you need to consider when debugging multithreaded code and applications that consist of more than one process Finally, I show you how to profile code Visual Studio NET does not provide a code profiler, but the NET Framework has support for providing profiling information through a user-supplied COM object I give an example of such a profiling object Appendix A The NET Framework class library is very comprehensive, and you’ll find code in it to perform just about any task you could previously with the C runtime library (CRT) or the standard C++ library In this appendix, I present, in a series of tables, the NET code that is equivalent to the most useful CRT functions and standard library classes The intention of this appendix is to provide a starting point for when you ask the inevitable question, “How I this in NET?” Appendix B This appendix is a personal list of further resources This list is not exhaustive, and I am sure that it is not the best list of NET resources However, I have provided the resources that were particularly useful to me, and I hope that you’ll benefit from them too This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com System Requirements The first five chapters require only the C++ compiler (version 13) The NET Framework SDK is a free download from Microsoft (msdn.microsoft.com/netframework) The C++ compiler supplied as part of the Framework SDK does not produce optimized code, nor does it provide extensions like the unmanaged ATL Attribute Provider, but it is a fully featured C++ compiler that can be used for both managed and unmanaged C++ development If you want to learn about the NET Framework, the C++ compiler is the place to start The last two chapters use features of Visual Studio NET Visual Studio NET includes the full optimizing C++ compiler, and it also comes with unmanaged libraries: the complete CRT library, the standard C++ library, and the combined ATL (ActiveX Template Library) and MFC (Microsoft Foundation Class) libraries, all of which you can access from NET code (msdn.microsoft.com/vstudio) Visual Studio NET also provides code wizards to create the initial files of your application, tools to manage your projects, a fully featured editor, and an integrated debugger If you intend to develop projects larger than a handful of classes, you should use Visual Studio NET This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Support Every effort has been made to ensure the accuracy of this book Microsoft Press provides corrections for books through the World Wide Web at the following address: http://www.microsoft.com/mspress/support/ To connect directly to the Microsoft Press Knowledge Base and enter a query regarding a question or issue that you might have, go to: http://www.microsoft.com/mspress/support/search.asp If you have comments, questions, or ideas regarding this book, please send them to Microsoft Press using either of the following methods: Postal Mail: Microsoft Press Attn: Programming with Managed Extensions for Microsoft Visual C++ NET Editor One Microsoft Way Redmond, WA 98052-6399 E-Mail: MSPINPUT@MICROSOFT.COM Please note that product support is not offered through the above mail addresses For support information regarding C++, Visual Studio NET, or the NET Framework, visit the Microsoft Product Standard Support Web site at: http://support.microsoft.com ... chapter, I show you how to use delegates with C++, how this approach compares with unmanaged function pointers, and how you can use delegates with unmanaged code I also explain how to make asynchronous... code written with Managed Extensions for C++ Chapter This document is created with a trial version of CHM2PDF Pilot http://www.colorpilot.com Visual Studio NET is a mixed managed and unmanaged application... is a primitive C++ type, and without gc an unmanaged pointer will be used It is interesting to note that in MSIL a managed pointer is identified with & whereas an unmanaged pointer is identified