develop-04 9010 October 1990
From the originals
13 scansMachine-transcribed text and image descriptions. Check the linked original for uncertain words or fine print.
These are transcribed pages from the documents, not the full publications. Open the original for the remaining pages.
Image 1
develop The Apple Technical Journal WRITING A DEVICE DRIVER IN C++ POLYMORPHIC CODE RESOURCES IN C++ SYSTEM 7.0 SNEAKS MACINTOSH Q & A DEVELOPER ESSENTIALS: ISSUE 4 APPLE II Q & A THE MACINTOSH NUBUS CARD AND A/ROSE PERILS OF POSTSCRIPT II APPLE IIGS PRINTER DRIVERS Issue 4 October 1990 Apple Computer, Inc.
A blue background with a collage of disassembled gold and silver watch movements, gears, hands, and a clock-face dial reading the days of the week, beneath a bold black masthead and a stacked list of article titles on the right.
Reading notes: The 'IIGS' in 'APPLE IIGS' uses a small-cap style 'GS' that may be rendered differently in the original; transcribed as IIGS. The 'II' in 'APPLE II Q & A' and 'APPLE IIGS' is shown with Roman numerals as printed. Small text on the dial in the artwork (days of the week) was not transcribed as page copy except as visual description.
- Printed product names
- develop · The Apple Technical Journal
- Printed dates
- October 1990
- Languages
- English
PDF page 1
d e v e l o p T h e A p p l e T e c h n i c a l J o u r n a l WRITING A DEVICE DRIVER IN C++ POLYMORPHIC CODE RESOURCES IN C++ SYSTEM 7.0 SNEAKS MACINTOSH Q & A DEVELOPER ESSENTIALS: ISSUE 4 APPLE II Q & A THE MACINTOSH NUBUS CARD AND A/ROSE PERILS OF POSTSCRIPT II APPLE IIGS PRINTER DRIVERS I ssue 4 October 1990 Apple Computer, Inc.
Reading notes: The masthead appears as letter-spaced text in the supplied extraction, so the headline spelling is uncertain. The reading order of the article titles is taken from the supplied extraction and may not match the cover layout. Article titles are listed as cover copy, not as advertised products. The text was supplied by local extraction and was not independently verified against the image.
- Printed dates
- October 1990
- Languages
- English
PDF page 2
© 1990 Apple Computer, Inc. All rights reserved. Apple, the Apple logo, Apple IIGS, AppleLink, AppleShare, AppleTalk, APDAlog, A/UX, GS/OS, ImageWriter, LaserWriter, Mac, Macintosh, MacDFT, MPW, MultiFinder, and TokenTalk are registered trademarks of Apple Computer, Inc. AppleEvents, APW, A/ROSE, Finder, MacAPPC, Macintosh Coprocessor Platform, and QuickDraw are trademarks of Apple Computer, Inc. IBM is a registered trademark of International Business Machines Corporation. PostScript is a registered trademark of Adobe Systems Incorporated. NuBus is a trademark of Texas Instruments. E D I T O R I A L Editor in Chief’s Clothing Louella Pizzuti Technical Buckstopper Dave Johnson Managing Editor Carol Westberg Production Editor Toni Haskell Developmental Editors Lorraine Anderson, Ann Cullen, Geta Carlson Editorial Assistant Lenore Zelony Indexer Ira Kleinberg Manager, Developer Press David Krathwohl A R T & P R O D U C T I O N Design/Art Direction Joss Parsey Technical Illustration J. Goldstein Production Bruce Potterton Printing Craftsman Press Film Preparation FilmCraft Photographer Ralph Portillo Circulation Management Dee Kiamy Online Production Cassi Carpenter R E V I E W B O A R D Pete “Luke” Alexander Tim “Sweetpea” Enwall Larry “Cat Couch” Rosenstein Andy “The Shebanator” Shebanow S P E C I A L T H A N K S Matt Deatherage Cleo Huggins and Hal Rucker created the cover with help from timekeepers past and present. Cover photograph by Ralph Portillo. d e v e l o p , The Apple Technical Journal, is a quarterly publication of Developer Press.
Reading notes: Transcript is intentionally empty because the exact extracted text is preserved separately. Visual description is inferred from the supplied extracted copy and was not verified against the image layout. The copy is an editorial masthead rather than an advertisement, so no advertised products or prices were listed; trademarked product names in the trademark notice were not treated as advertised products. The only printed date is the copyright year 1990 in the notice.
- Printed dates
- 1990
- Languages
- English
PDF page 3
Writing a Device Driver in C++ (What? In C++?) by Tim Enwall How to capitalize on the advantages of a higher level language and avoid some of the pitfalls you may encounter if you write a driver in C++, including a complete example of a device driver in C++. 376 Polymorphic Code Resources in C++ by Patrick C. Beard A method of implementing polymorphism in stand-alone C++ code resources, illustrated by a window definition function that uses polymorphism. 400 System 7.0 Sneaks Answers from Apple Computer. 413 Macintosh Q & A Answers from the Macintosh DTS group. 417 Developer Essentials: Issue 4 The latest disc containing essential tools for developers. 420 Apple II Q & A Answers from the Apple II DTS group. 422 Inside the Macintosh Coprocessor Platform and A/ROSE by Joseph Maurer An introduction to the basics of the Macintosh NuBus card and A/ROSE (the Apple Real-time Operating System Environment). Includes a close look at interprocess communication in A/ROSE and how the TokenTalk card uses A/ROSE, plus some samples of A/ROSE programming. 424 The Perils of PostScript—The Sequel by Scott “Zz” Zimmerman A description of some gotchas that can occur when you use PostScript dictionaries in applications, and ways to work around them. 446 Driving to Print: An Apple IIGS Printer Driver by Matt Deatherage An explanation of the mysteries of the printer driver: what it does, how it does it, and how to write one. A sample printer driver is provided. 454 Index 478 CONTENTS CONTENTS October 1990 373
Reading notes: Table of contents layout makes reading order and page-number associations uncertain. Some entries use inconsistent punctuation and dash characters that may be OCR artifacts.
- Printed product names
- Developer Essentials: Issue 4 · Apple II · Macintosh · Apple IIGS
- Printed dates
- October 1990
- Languages
- English
PDF page 4
Dear Readers, I just got back from sabbatical and it was great: I left and could hardly remember that I had ever worked for Apple, and now that I’m back I can hardly remember that I ever left. It’s good, I think, to be fully where you are as you linger. Upon my return, I wasn’t quite sure how, in my advanced state of equilibrium, I was going to find a way for drivers and clock parts to live together in a logical editorial. So I decided to throw logic out the window and to stick with what I know: taking an analogy and stretching it. Here goes. Clock parts are carefully crafted according to well-defined rules. Along with following the rules, creativity and craftsmanship are brought to bear, so some clocks are more pleasing, better functioning, and longer lasting than others. This is how it is with drivers, too. Respect for the rules, creativity, and craftsmanship combine to make a driver tick. Clock parts as a group (or a watch) keep track of the moment-by-moment passage of time, freeing us to focus our attention on things more riveting. Similarly, a system- level driver lets your application focus on things more interesting (and useful) than hardware-specific details. So much for the analogy. In this issue, Matt provides thorough coverage of the printer driver: what it does, how it does it, and how to write one for the Apple IIGS Zz tells even more about what your application can do with PostScript code to avoid perils posed by the LaserWriter driver. And if you decide to write your own driver, you can follow the legions before you and launch into assembly language, or you can follow Tim’s lead and try C++. On another topic, Scott A. Williams writes: “On page 126, I believe that the AllocHeap method call to InitZone should have calls to GetZone and SetZone around it, like this: THz savedZone = GetZone (); InitZone(nil, kNumDfltMasters, limitPtr, zonePtr); SetZone(savedZone); d e v e l o p October 1990 COMMENTS We welcome timely letters to the editor, especially from readers wishing to react to articles that we publish in develop. Letters should be addressed to Louella Pizzuti, 20525 Mariani Ave., M/S 75-3B, Cupertino, CA 95014 (AppleLink Pizzuti1). All letters should include name and company name as well as address and phone number. Letters may be excerpted or edited for clarity (or to make them look like they say what we wish they did). • 374
Reading notes: Scott A. Williams quoted code is partially garbled by spacing, possibly OCR artifacts. Page number '374' appears at the end of the copy with uncertain placement.
- Printed product names
- Apple IIGS · LaserWriter · PostScript · AppleLink
- Printed dates
- October 1990
- Languages
- English
PDF page 5
“Inside Macintosh, volume II, page 29, says, ‘ InitZone creates a new heap zone, initializes its header and trailer, and makes it the current zone.’ It’s the ‘makes it the current zone’ part that’s the problem. Without the calls to GetZone and SetZone , any handles or pointers created after a call to the AllocHeap method would be allocated in the new heap created expressly for holding PtrObjects and not in the application heap where they belong.” Well, when Scott wrote he was right, and now he’s sporting a fine new develop shirt. When you write, you will too. Louella Pizzuti Editor EDITORIAL October 1990 375 SUBSCRIPTION INFORMATION Use the order form on the last page of the journal to subscribe to develop. Please address all subscription (and subscription-related) inquiries to develop, Apple Computer, Inc.,P.O. Box 531, Mt. Morris, IL 61054, (AppleLink Dev.Subs). • BACK ISSUES Back issues of develop are available through APDA (see inside back cover for APDA information), and are, of course, there for the browsing on each CD. •
Reading notes: Headline unclear: no distinct primary heading identified in the source copy
- Printed product names
- Inside Macintosh · develop
- Printed dates
- October 1990 · 1990 · volume II · page 29
- Languages
- English
PDF page 6
WRITING A DEVICE DRIVER IN C++ (WHAT? IN C++?)
TIM ENWALL Most developers write device drivers in assembly language, rarely considering a higher level, object-based language such as C++ for such a job. This article describes some of the advantages of higher level languages over assembly and warns of some of the gotchas you may encounter if you write a driver in C++. An example of a device driver written in C++ follows a brief discussion of drivers in general. When you think of writing a device driver, your first reaction may be, “But I haven’t brushed up on assembly language in some time.” After taking a deep breath, you think of another approach: “Why can’t I use a high-level language?” You can. One such language is C++. In comparison with standard C, C++ offers some definite advantages, including ease of maintenance, portability, and reusability. You can encapsulate data and functions into classes, giving future coders an easier job of maintaining and enhancing what you’ve done. And you can take advantage of most (but not all) of the powerful features of C++ when you write stand-alone code. You will run into a few gotchas, including the fact that polymorphism is available only if you do some extra work (for a definition of polymorphism, see develop, Issue 2, page 180). Because the virtual tables (vTables) reside in the jump-table segment, a stand-alone code resource can’t get at the vTables directly (more on this topic later). You also have to deal with factors such as how parameters are passed to methods, how methods are called, how you return to the Device Manager, how you compile and link the DRVR resource, and how the DRVR resource is installed when the machine starts up. We’ll tackle some of these obstacles as we work through the sample device driver presented later in this article. WRITING A DEVICE DRIVER IN C++ (WHAT? IN C++?) d e v e l o p October 1990 TIM ENWALL, DTS engineer, is a four-year Apple veteran. He’s done stints in Technical Resources and data base applications, and has answered the A/UX ® hotline. Now his primary job purportedly revolves around IBM connectivity (although no one ever seems to ask him about it). The rest of his time is spent with networking and lower-level device managers. A Rocky Mountain native, he came to Cal Berkeley for an EE/CS degree. He likes bike riding, cooking, playing softball, and long talks with friends. Two Burmese cats—Bella and GBU (for the Good, the Bad, and the Ugly, pronounced “Boo”)—guard him during his off hours. Two favorite books have helped 376
Reading notes: Running headers and page numbers are interleaved with body text, so reading order at column breaks may be uncertain.
- Printed product names
- C++ · C · A/UX · IBM · Apple · develop
- Printed dates
- October 1990 · Issue 2
- Languages
- English
PDF page 7
WHY C++? When someone suggests writing a device driver in anything other than assembly language, the common reaction is, “But you’re talking to a device! Why would you want to use C++?” For communication with devices, assembly language admittedly gets the job done in minimal time, with maximum efficiency. But if you’re writing something where code maintenance, portability, and high-level language functionality are just as important as speed and efficiency, a higher level language is preferable. Not all device drivers actually communicate with physical devices. Many device drivers have more esoteric functions, such as interapplication communication, as in the sample driver in this article. (In fact, DAs are of resource type DRVR and behave exactly the same way device drivers behave. DAs are even created the same way.) For these kinds of device drivers, C++ is a great language to use because you can take advantage of all the features of a high-level language, plus most of the object-based features of C++. Finally, device drivers have some nice features that make them appealing for general usage: • They can remain in the system heap, providing a common interface for any application to easily call and use. • They get periodic time (if other applications are not hogging the CPU). Good examples of nondevice drivers are the .MPP (AppleTalk ® ) driver and the .IPC (A/ROSE™ interprocess communication) driver. Both these drivers provide pretty high-level functionality, but neither directly manipulates a device as such (except for the very low-level AppleTalk manipulations of communication ports). Of course, if you were writing code to communicate quickly and efficiently to a modem, for example, assembly language might be the better choice, depending on your need for efficiency and timing. For the purposes of this article, any reference to a device driver includes both types of drivers. Clearly, higher level languages have a place, but what about object-based languages? Object-based languages provide a great framework for encapsulation of data and functions and hence increase the ease of maintenance and portability (if used elegantly). One question still remains: Why C++? Notables such as Bjarne Stroustrup and Stanley Lippman have pointed out some of the advantages C++ offers over conventional high-level languages. C++ offers great extensions, such as operator and function overloading, to standard C. C++ is much more strongly type checked than C, so it saves us programmers from ourselves. C++ classes offer a way to encapsulate data—and functions that operate on the data—within one unit. You can make different elements and functions “private” to objects of only one class or “public” to objects of every type. The private and public nature of data and member functions allows you to accomplish real encapsulation. WRITING A DEVICE DRIVER IN C++ (WHAT? IN C++?) October 1990 377 shape his outlook: Light in August by William Faulkner and Native Son by Richard Wright. But don’t let his serious side fool you. Watch out when he’s sitting across a poker table from you: he was brought up on cards, and he’s out to get that BMW 3.0CSi with a sunroof. Will you be the one to provide the down payment? •
Reading notes: Text begins mid-sentence ('377 shape his outlook:'), suggesting a fragmented reading order from a magazine page layout. Fragment mixing an article about device drivers with an unrelated advertisement-style passage; boundary between them is unclear.
- Printed product names
- BMW 3.0CSi
- Printed dates
- October 1990
- Languages
- English
PDF page 8
SOME LIMITATIONS As noted, one valuable feature of C++, polymorphism, is not readily available when you write a device driver in C++. Other limitations involve working with assembly language, possible speed sacrifices, work-arounds for intersegment calls, and mangled procedure names. POLYMORPHISM Because a device driver is a stand-alone code resource, there is no “global” space or jump table. C++’s virtual function tables (vTables), which are the means to the polymorphism end, live in an application’s global space. The loss of virtual tables is a limitation of stand-alone code, not a limitation of C++. Patrick Beard’s article, “Polymorphic Code Resources in C++” (this issue), shows one way to work around this limitation. The work-around takes some extra work and is dependent on the current implementation of CFront, which may make future compatibility a problem. In the interests of clarity and compatibility, I have chosen not to use polymorphism for the example in this article. ASSEMBLY-LANGUAGE MUCK Another difficulty is that we have to get our hands assembly-language dirty. The Device Manager is going to call the device driver with a few registers pointing to certain structures, and we’ll have to put those on the stack so the C++ routines can get to them. Specifically, A0 points to the parameter block that is being passed, and C++ Assembly Language Pros Portable Fast Reusable Efficient Easy to maintain Compact Object-based design Direct access to CPU High-level language features Data encapsulation Cons Three separate source files, Not portable multiple compiles Hard to maintain Speed inefficient Lacking high-level language Polymorphism difficult features such as loops in stand-alone code and IF-THEN-ELSE COMPARING C++ AND ASSEMBLY LANGUAGE d e v e l o p October 1990 378
Reading notes: Reading order around the C++ vs. Assembly Language comparison table is uncertain, as its columns are interleaved in the extracted text.
- Printed dates
- October 1990
- Languages
- English
PDF page 9
A1 has a handle to the Device Control Entry for the driver. Having to do some assembler work is a limitation of the operating system; the toolbox doesn’t push the parameters onto the stack (now if there were glue to do that—). These registers must somehow make their way onto the stack as parameters to our routines because procedures take their parameters off the stack. When we’ve finished, we also have to deal with jumping to jIODone or plain RTSing , depending on the circumstances. For the simple driver shown in the example, we will in reality almost always jump via jIODone when finished with our routines. But, for drivers that wish to allow more than one operation at a time, the Prime , Control , and Status calls must return via an RTS to signal the Device Manager that the request has not been completed. The driver’s routines should jump to jIODone only when the request is complete. We must also decide whether or not to call a C++ method directly from the assembly language “glue.” If we call the method directly, we have to put the “this” pointer on the stack because it’s passed implicitly to all object methods. We also have to use the “mangled” name generated by the compiler and used by the linker. (If you haven’t had the opportunity to see mangled names, you’ll find they’re a joy to figure out without the help of our friend Mr. Unmangle.) So, if we choose to call extern C functions, as the example does, we run into yet another level of “indirection” before we get to the real meat of the matter. SPEED Some might say we sacrifice speed as well as efficiency—and they’re correct. In general, compilers can’t generate optimally speed-efficient code. They can come close, but nothing even approaches how the human mind tackles some tricky machine-level issues. Thus, we’re at the mercy of the compiler—the loss of speed is the result of the compiler’s inefficiency. You’ll probably find the sample driver presented in this article pretty inefficient. But the trade-off is acceptable because speed isn’t important in this case, and you can use all the features of an object-based language. In fact, in most instances you can limit assembly language to a few routines, which must be tightly coded, and use C++ for the rest. MANGLED IDENTIFIERS If you’re familiar with C++, you’ve undoubtedly seen the visions of unreadability created by CFront. But, if you’re still unfamiliar with C++ in practice, here’s an explanation. CFront is simply a preprocessor that creates C code, which is passed to the C compiler. So CFront has to somehow take a function of the form TDriver::iacOpen(ParmBlkPtr aParmBlkPtr) and create a C function name the C compiler can understand. The problem is that when the linker complains, it will use the mangled name, which is hard to decipher. WRITING A DEVICE DRIVER IN C++ (WHAT? IN C++?) October 1990 379
Reading notes: Page number '379' and running header interleaved with body text; reading order near page break is clear but header placement is uncertain
- Printed dates
- October 1990
- Languages
- English
PDF page 10
Here’s how it looks: from MPW Shell document unmangle iacOpen__7TDriverFP13ParamBlockRec Unmangled symbol: TDriver::iacOpen(ParamBlockRec*) It’s clear why these names are referred to as mangled and unmangled. Fortunately, the unmangle tool provided with MPW allows you to derive the unmangled name from the mangled. A SAMPLE C++ DRIVER The sample driver that follows illustrates some of the issues involved in writing a device driver in general, and specifically in C++. The code is in the folder labeled C++ Driver on the Developer Essentials disc. INTERAPPLICATION COMMUNICATION The sample driver performs one basic function—interapplication communication (IAC)—under System 6. Under System 7 the services of this sample driver aren’t necessary because IAC is built into the system. But the concepts presented here are still sound, and the driver works as well under System 7 as it does under System 6. The driver is installed at Init time with code that walks through the unit table looking for a slot. CLASS STRUCTURE The classes are fairly straightforward, serving as an example of how to use C++ to encapsulate data with methods without getting into some gnarly class hierarchies that would only obfuscate the point (and that aren’t yet possible with stand-alone code). Two classes suffice: TDriver and TMessage . TDriver handles all the driving; it responds to each control and status call defined and handles opening and closing the driver. It keeps two simple data structures—an array of application names that have registered and an array of TMessage pointers that need to be received. TMessage handles the messages—who they’re from, who they’re addressed to, and what the message is. I think you’ll find the declarations easy reading. from TDriver.h class TDriver: public HandleObject { public: // Constructor and destructor. TDriver(); ~TDriver(); d e v e l o p October 1990 380
Reading notes: Source appears to be a technical programming article excerpt with code fragments, not advertising copy.
- Languages
- English
PDF page 11
/* Generic driver routines. These are the only public interfaces we * show to the world. */ OSErr iacOpen(ParmBlkPtr oParmBlock); OSErr iacPrime(ParmBlkPtr pParmBlock); OSErr iacControl(ParmBlkPtr cntlParmBlock); OSErr iacStatus(ParmBlkPtr sParmBlock); OSErr iacClose(ParmBlkPtr cParmBlock); private: // Control Routines. /* RegisterApp takes the string in iacRecord.appName and finds a slot * in the array for the name (hence it "registers" the application). * SendMessage sends a message from one application to another (as * specified by the iacRecord fields). * ReceiveMessage puts the message string into the iacRecord.msgString * field if there’s a message for the requesting application. * UnregisterApp removes the application’s name from the array (hence * the application is "unregistered"). */ short RegisterApp(IACRecord *anIACPtr); short SendMessage(IACRecord *anIACPtr); short ReceiveMessage(IACRecord*anIACPtr); short UnregisterApp(IACRecord *anIACPtr); // Status Routines /* WhosThere returns the signature of other applications that * have registered. * AnyMessagesForMe returns the number of messages waiting for the * requesting application in iacRecord.actualCount. */ void WhosThere(IACRecord *anIACPtr); Boolean AnyMessagesForMe(IACRecord *anIACPtr); // Message array handling routines. /* GetMessage gets the TMessPtr in fMessageArray[signature]. * SetMessage sets the pointer in fMessageArray[signature] to * aMsgPtr. */ TMessPtr GetMessage(short signature); void SetMessage(short index, TMessPtr aMsgPtr); // AppName array handling routines. /* GetAppName gets the application name in fAppNameArray[signature]. * SetAppName sets the application in fAppNameArray[signature] * to anAppName. */ char *GetAppName(short signature); void SetAppName(short signature, char *anAppName); WRITING A DEVICE DRIVER IN C++ (WHAT? IN C++?) October 1990 381
Reading notes: Source appears to be a code listing with comments; primary heading not clearly printed.
- Printed dates
- October 1990
- Languages
- English