0% found this document useful (0 votes)
970 views

C++ For VB Programmers: Apress Media, LLC

Uploaded by

dangki2209
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
970 views

C++ For VB Programmers: Apress Media, LLC

Uploaded by

dangki2209
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

C++ for VB Programmers

JONATHAN MORRISON

APress Media, LLC


C++ for VB Programmers
Copyright © 2000 by Jonathan D. Morrison
Originally published by Apress in 2000

Additional material to this book can be downloaded from http://extras.springer.com


All rights reserved. No part of this work may be reproduced or transmitted in any
form or by any means, electronic or mechanical, including photocopying, record-
ing, or by any information storage or retrieval system, without the prior written
permission of the copyright owner and the publisher.

ISBN 978-1-893115-76-7 ISBN 978-1-4302-0858-7 (eBook)


DOI 10.1007/978-1-4302-0858-7

Trademarked names may appear in this book. Rather than use a trademark sym-
bol with every occurrence of a trademarked name, we use the names only in an
editorial fashion and to the benefit of the trademark owner, with no intention of
infringement of the trademark.

Editorial Directors: Dan Appleman, Gary Cornell, Karen Watterson


Technical Reviewer: Dan Appleman
Editors: Katharine Dvorak and Kristen Brown
Projects Manager: Grace Wong
Supervising Production Editor: MaryAnn Brickner
Production Services and Page Composition: Impressions Book and Journal
Services, Inc.
Artist: Frank Giangreco
Cover: Karl Miyajirna

The information in this book is distributed on an "as is" basis, without warranty.
Although every precaution has been taken in the preparation of this work, nei-
ther the author nor Apress shall have any liability to any person or entity with
respect to any loss or damage caused or alleged to be caused directly or indirectly
by the information contained in this work.
Acknowledgments
THIS IS THE SECTION OF THE BOOK THAT IS probably only read by those who are
named in it, so I will try to stay informal. Here it goes:
First and foremost, I want to thank my Lord and Savior, Jesus Christ, for giv-
ing me the opportunity, talent, and stamina necessary to write this book (don't get
nervous I'm not going to start preaching!), and for placing me with Apress, home
of the best technical book people around. To my wife Kelly, thank you for being
my source of encouragement and inspiration throughout this difficult book-
writing experience, and more importantly, throughout my whole life. You have
made it possible for me to write this book by being able to simultaneously run our
household, keep track of our two-year-old son and carry the newest addition to
our household in your womb all by yourself, while I was busy writing. Thank you
honey, I love and appreciate you more than you know (or I show)! I am absolutely
the luckiest man alive. You are my soul mate and my existence. I would also like to
thank my two-year-old son Joda, for being a constant reminder that even
though writing a programming book is important, it pales in comparison to the
importance of being a dad. I would like to thank my, as yet unborn, second
child-PumpkinDoodle-as named by Joda for the last nine months of joyous
planning and anticipation. (Update: Joda is now 4 years old and as beautiful as
ever-although he now prefers C# to C++. And PumpkinDoodle actually was
born, although his given name had to be changed, because PumpkinDoodle
didn't fit on the birth announcements, to Journey Guy Morrison).
Thanks to everyone at Apress. It was truly an honor to write for such a
first-class publishing company. Special thanks to Dan Appleman for doing an in-
credibly thorough (and sometimes humbling) technical review and for always
being available to answer my questions. Also thanks to Dan for writing the best
technical books I have ever read. It was truly wonderful to work with such an
awesomely talented person. Thanks to Gary Cornell for answering all of my
"novice author" questions and for helping me and encouraging me through the
whole writing process in general. Also to Grace Wong for being a patient, kind,
and dedicated project manager, who was always available to listen to my ques-
tions and concerns regardless of how ridiculous most of them were. And thanks
to my buddy Frank Giangreco for doing all of the illustrations.
Next I would like to thank those that have mentored me either technically,
professionally, or both, along the path of my career. To Keith Yarnell, thanks for
believing in me and teaching me how to think like a programmer, not just to write
programs. You gave me the foundation on which I have built my career. Thanks to
Dr. Phyllis Chasser for teaching me about computer science in general, but more
for being a good friend and always supporting me. Special thanks to Priscilla

iii
Acknowledgments

Murphy (Aunt 'Cilia) for making me finish school instead of going on tour with my
rock band, although I still have my spandex and hairspray in the closet just in
case this programming thing doesn't work out. Thanks to Roger Collins for con-
stantly challenging me with some of the wildest C++ problems I have ever seen,
and for never accepting "just good enough" from me. I would also like to thank Ed
Martin for helping me prepare mentally for the challenges of writing a technical
book and explaining the various subtleties of the publishing business. To two of
the most talented programmers I know, and two of my closest friends, Lazaro
Ballesteros and Gilbert Rosal, thanks for everything guys! You have been a source
of encouragement and inspiration to me always.
I would like to thank Berry (like strawberry) Crook from the Maxim Group for
all of the "free" sushi lunches and other various encouragements along the way.
Last but not least, I want to thank my family for standing behind me and always
believing in me. My mom, Deborah Morrison, I love you as if you were my own
mother (Ha Ha!)! I love you mom. My sisters, Sarah, Rachel, Mary, and Hannah,
I love each and every one of you with all my heart. I hope that I have been as much
of an inspiration in your lives as you have been in mine. My grandmother, Evelyn
Bozeman, you are the most "practical" person I know, and I wouldn't change a thing
about you. Thank you for loving me and believing in me even though you didn't al-
ways understand me. To my favorite (and only) uncles, Donald and Ray. Thanks for
allowing me to learn many of life's lessons at your expense-construction in partic-
ular (sorry about the "French door" incident Uncle Donald). You both were great
influences on my life. My "other" parents (a.k.a. in-laws), Chip and Barbara Plank,
thanks for making me a part of your family, and loving me as such. You are both very
near and dear to my heart. To my "other" sisters, Kara Plank (who I can still beat at
any water sport in existence today!) and Kristen Brown (who's hard editing work
made this book even better than it should have been), I love you both. To my "other"
brother (and international finance genius) Don Brown for the golf lessons and his
general great-guy-ness. I love you Man! To "Doc" (a.k.a. Dr. James K. Isom, veteri-
narian extraordinaire!), you have been like a father to me and always encouraged
Kelly and me in all of our endeavors. You will always hold a special place in our
hearts. You truly have made a huge difference in my life and for that I love and
thank you. To my closest friend and the best drummer in the world, Doug Miller,
thanks for all of the free therapy sessions and the lifetime of great memories. You are
a part of who I am today. To David Verost, thanks for always being there. I consider
you both closer to me than brothers. And to the two men who took a part of me
when they passed away: my granddaddy, Robert Guy Bozeman, and my father,
Lewis Alvyn Morrison. I wish that both of you could have been here to share this
happiness with me, but I know that you are in a better place today. I love, miss, and
think about you every day of my life.

iv
Foreword
by Dan Appleman

"SHAME! SHAME!"- I CAN HEAR MY FRIENDS CRY. "How could you, of all people,
write a foreword for a book that teaches Visual Basic programmers to work in
C++?"
I can see their point. After all, I have built much of my career on the idea that
Visual Basic is the best language for Windows development. My own company,
Desaware, is dedicated to providing tools that extend the power ofVB to the point
where programmers can do virtually anything they want without having to use
C++.
Why then, would I not only write a foreword to a book that teaches C++, but
act as the technical reviewer for the book as well? What could lead to such a radi-
cal change in approach?
Sorry to disappoint you, but in fact my approach to Windows software devel-
opment has not changed at all. I continue to be a strong advocate ofVB as the
best software development platform for most Windows applications. But I have
never suggested that it is the best language for all Windows development. There
are many tasks that are better done in C++, and some that can only be done in
C++. For example, most ofDesaware's components that extend the reach ofVB are
written in C++ using Microsoft's Active Template Library CATL) and the exact tech-
niques that you will soon read about in this very book.
What I have opposed, and continue to oppose, is the idea that the choice of
language is an all or nothing proposition. The idea that C++ is the best tool for
creating Windows user interfaces is, in my mind, as silly as the idea that VB is the
best tool for creating ultra high-speed pixel manipulation routines. The ideal Win-
dows software development environment is, and always has been, one that allows
you to use the right tool for each job that comes along. Visual Basic alone may be
a nice language, but what makes it truly great is its ability to seamlessly integrate
code written in C++ or other languages using components or external DLL calls
with the Declare statement.
I believe many VB programmers would agree that mixed language program-
ming is the best strategy for software development in Windows. Unfortunately,
learning C++ represents quite an investment in time and effort-an insurmount-
able obstacle to many.
But why should this be? After all, as a language, C++ is in many ways simpler
than VB. It has far fewer keywords to memorize. Why is it so hard to learn?

v
Foreword

Well, one reason is that every book on beginning Visual C++ that I have seen
focuses on using MFC to build C++ applications. That huge library is enough to
intimidate anyone. And every line of every book that discusses MFC is a complete
waste of time for VB programmers! Why should they learn to create user interfaces
and dialog boxes using C++ when, in fact, smart VB programmers can create any
user interface they need using VB and a handful of components, and do so in a
fraction of the time with a fraction of the effort?
No, what VB programmers want and need is an introduction to C++ that al-
lows them to write small, high performance code routines that can be called from
their VB applications. In other words, what most VB programmers really want is
the ability to create their own DLLs, and expose either function libraries or COM
objects that can be used by their main VB application.
As I reviewed this book, I was impressed by how closely Jonathan focused on
the real needs ofVB programmers. The introduction to the C++ language assumes
no prior knowledge of C++, but it doesn't waste time teaching concepts that every
VB programmer already knows. He covers the fundamentals of classes and ex-
porting functions from DLLs, and how to call them from VB. Then he shows how
to use ATL to build COM components for use with VB.
This book won't turn you into a C++ expert. It won't turn you into an ATL ex-
pert. But that's the whole point-you don't need to be an expert to solve most of
the problems that VB programmers want to address with C++. You just need to
know enough to solve a problem. This book will teach you what you need to know
and not make you waste your time learning techniques and class libraries that
you're better off doing in VB anyway.
I think this book will make a real contribution to the VB community. I'm glad I
had the privilege of reviewing it. I hope you enjoy it as much as I did.

vi
Contents at a Glance
Introduction • • • xiii

Chapter 1 Why C++? (And Why with Visual Basic) • •1

Chapter 2 Where Do We Start? . . . . . .5

Chapter 3 How Do You Do That Voodoo That You Do? . . • . . 17


Chapter 4 C++ 101 . • . . • • • . . . • . . . . . • • . •33
Chapter 5 It's Not Polite to Point . . . . . 67

Chapter 6 Classes • • . • • . . . . . . . 81

Chapter 7 Templates . . . . . .109


Chapter 8 Putting It All Together . . . . . . . . .123

Chapter 9 What's the DLL, Man? . . . . . . . . . . . . .169

Chapter 10 Your First Real DLL .183


Chapter 11 An ATL Primer .225
Chapter 12 The COM Project . . . . . . . . . . 241

Chapter 13 Advanced Topics .277

Appendix A A Thread to Visual Basic . . . . . • • . .301


Appendix B Visual Basic Strings: The BSTR Data Type .323
Appendix C Article 3. Strings the OLE Way . . 335
Index . . . . . . . . . . . . . . . . . . . . . • • . • • 367

vii
Contents

Introduction .xiii

Focus and Benefits ................................................... xiii


Style of Presentation ................................................. xiv
Prerequisites ........................................................ xiv

Chapter 1 Why C++? (And Why with Visual Basic) . . . . . .1

Why Visual Basic Was Created .......................................... 2


The Next Step ......................................................... 4
Conclusion ........................................................... 4

Chapter 2 Where Do We Start? . . . . . . . . . . . . . . .5

Visual Studio ......................................................... 5


C++ Runtime Environment ............................................ 9
Visual C++ Debugging Environment ................................... 11
Conclusion .......................................................... 15

Chapter 3 How Do You Do That Voodoo That You Do? . . . • •17


Compiling .......................................................... 18
Linking ............................................................. 20
C Preprocessor ...................................................... 21
Memory ............................................................ 27
Conclusion .......................................................... 31

I
Chapter 4 C++ 101 . . . . . . . . . . . . . . . . . . . . 33

Data and Variables ................................................... 33


Standard Library Functions ........................................... 38

ix
Contents

Program Structure ................................................... 40


Operators ........................................................ ... 50
Loops and Control Statements ........................................ 61
Conclusion ........................................................ .. 66

Chapter 5 It's Not Polite to Point . • . . . . . • . . . . 67

What Is a Pointer? .................................................... 67


Allocating Memory for Pointers ....................................... 73
Strings and Char Pointers ............................................. 75
Conclusion ........................................................ .. 79

Chapter 6 Classes . . . . . . . . . . . . . . . . . . . . 81

Class Dismissed ..................................................... 81


C++ Classes ........................................................ . 88
Inheritance ........................................................ .. 97
Conclusion ........................................................ . 108

Chapter 7 Templates • . . . • . . . . • . . . . . . . . • 109


UnderstandingTemplates ........................................... 109
Using a Template Class .............................................. 115
Conclusion ........................................................ . 121

Chapter 8 Putting It All Together • • • • • • . . • • . . 123

The Application Requirements ....................................... 123


The Application Design .............................................. 123
The ffieBreaker.cpp File ............................................. 157
Conclusion ........................................................ . 167

Chapter 9 What''s the DLL, Man? . . . . . . . . . . . . .169

When a DLL is Not Really a DLL ...................................... 169


The Basics ofDLLs .................................................. 170
Conclusion ........................................................ . 182

X
Contents

Chapter 10 Your First Real DLL . . . . . . . . . . . . .183

TrayMan.DLL ...................................................... 183


Creating the TrayMan.DLL Interface .................................. 189
ImplementingTrayMan.DLL ......................................... 201
The Client Application .............................................. 215
Conclusion ......................................................... 223

Chapter 11 An ATL Primer . . . . . . . . . . . . . . . . 225

COM and Interfaces ................................................. 225


ATL ................................................................ 228
Conclusion ......................................................... 240

Chapter 12 The COM Project . . . . . . . . . . . . . . . 241

Creating the Project ................................................. 241


Adding the Methods ................................................ 243
Implementing the Interface .......................................... 249
Looking at the Client Application ..................................... 268
Conclusion ......................................................... 276

Chapter 13 Advanced Topics . . . . . . . . . . . . . . . 277

The DLLMain Function .............................................. 277


Multithreading ..................................................... 280
Sharing Data in a DLL ............................................... 295
Scripting the IDE ................................................... 297
Conclusion ......................................................... 300

Appendix A A Thread to Visual Basic 0 0 0 0 0 301

Just Because You Can, Doesn't Always Mean that You Should ............ 301
A Quick Review of Multithreading .................................... 302
The Threading Contract ............................................. 310
The CreateThreadAPI ............................................... 312
The CreateThreadAPI Revisited ...................................... 316
Conclusion ......................................................... 320

xi
Contents

Appendix 8 Visual Basic Strings: The BSTR Data Type •• . 323

What Is a BSTR? .................................................... 323


Using _bstr_t ....................................................... 325
Conclusion ........................................................ . 333

Appendix C Article 3. Strings the OLE Way . . . . . . . . 335

Unicode Versus ANSI ................................................ 336


What Is a BSTR? .................................................... 340
The String Class .................................................... 349

Index . . . . . . . . . . . . . . . . . . . . . . . . . . 367

xii
Introduction
ONE OF MY GREATEST FRUSTRATIONS AS a newbie Visual Basic programmer was the
fact that while 90 percent of the functionality I wanted was available directly from
Visual Basic, the remaining 10 percent was trapped in the Win32 API, which I had
no idea how to use. Luckily, I discovered Dan Appleman's Visual Basic Program-
mers Guide to the Win32 API (Sams, 1999), which I read from cover to cover twice!
I could not believe that all of the great functionality from the WIN32 API was at
my disposal right from good old Visual Basic.
Instead of curbing my appetite, however, Dan's book made me want to learn
even more. I was no longer satisfied with simply calling the Win32 API; I wanted
to be able to write my own API. I realized that in order to achieve the level of
knowledge I wanted to have, I would need to learn C++. So I started reading every
CIC++ book I could get my hands on, but I was usually disappointed with the
content. The books were either so basic they were useless for teaching me what I
wanted to know or they were so advanced I couldn't grasp the concepts presented
(which meant that they didn't help me at all in my ultimate quest-to become a
more effective Windows programmer).
Finally, I gave in and learned C++ from scratch, and thereby ignored every-
thing I already knew about programming for Windows with Visual Basic. This
drastically increased the time I had to spend learning C++. I hope that no other
Visual Basic programmer has to learn C++ the way I did. In fact, it is for this very
reason I wrote this book. I don't believe that your existing knowledge ofVisual
Basic should be negated just because you're trying to learn C++. In fact, it should
be exploited in order to reduce the time required to attain this new skill.
Most Visual Basic programmers want to learn C++ in order to enhance the ap-
plications they are writing in Visual Basic-not to replace them with applications
written in C++. Being able to write DLLs that take advantage of C++'s low-level ca-
pabilities, having access to API's that use types not supported in Visual Basic, and
writing ActiveX components that don't require a huge runtime library are a few
examples of how knowing C++ can enhance your effectiveness as a Windows pro-
grammer. And that is the goal of this book: to make you a more effective Windows
programmer.

Focus and Benefits


The focus of this book is to teach you how to use C++ to enhance your Visual Basic
development efforts. However, with the knowledge you will gain after completing

xiii
Introduction

this book, you should be able to create many different types of solutions using
Visual Basic and C++.
The main benefit you will realize from this book is a solid knowledge of the
C++ programming language as well as a good understanding of the internal work-
ings of the Windows operating system(s). This knowledge can then be built upon
with other books and learning resources.

Style of Presentation
With apologies to my various English teachers over the years, this book is written
in the first person. Why? Because I think technical books written in the first per-
son are much easier to read and follow than books that are not. I've tried to write
the chapters of this book as if I were speaking to you in persori. I hope you find
the content easier to understand this way.

Prerequisites
For this book to be effective, you should have a good handle on Visual Basic syn-
tax. This is because I use Visual Basic to explain the language elements of C++. You
don't need to have any prior knowledge of C or C++, but familiarity with the
Win32 API is a plus. There will be some advanced Visual Basic code used to ex-
plain some concepts in a few of the chapters, but I will go through them in detail
when we get there.
Finally, you will also need Visual C++ 6.0 Introductory Edition (included on
the CD-ROM that accompanies this book) or higher (Professional and Enterprise
Editions), if you wish to work through the code samples on your own. All of the
sample code I use throughout this book may be found on the book's accompany-
ing Web site at http: I /www. a press. com.
Other than that you just need some willpower and hunger for knowledge!

xiv

You might also like