TweetFollow Us on Twitter

Oct 99 Getting Started

Volume Number: 15 (1999)
Issue Number: 10
Column Tag: Getting Started

Catching up with Carbon

by Dan Parks Sydow

The Current State of the Carbon API

Back in January of this year we looked at Apple's then-new Carbon - the application programming interface (API) meant to be a replacement for the Macintosh Toolbox. At that time we said that Carbon existed so that a programmer could write an application that would run on either a Mac hosting Mac OS 8 or on a Mac hosting the upcoming Mac OS X. That's still true. But now, with the release of Mac OS 9 from Apple and the release of support files from Metrowerks, a programmer can move from theory to application. Carbon isn't completely finalized, but the bulk of it is in place. So now you can start writing and compiling code to verify that your program is indeed Carbon compliant.

About Mac OS X and Carbon

If you aren't at all familiar with Mac OS X or with Carbon, and you have access to the Getting Started article in the January 1999 issue of MacTech, go ahead and give it a read. If you don't have that article, or just want a very quick summary of these two Apple software technologies, make sure to read this section.

Mac OS X is the soon-to-be-released version of the Mac operating system that is to bring on important and necessary enhancements that both programmers and users have been waiting for. Chief among those improvements are increased stability (via a protected address space for each process, or running application), increased responsiveness (by way of preemptive multitasking so that the processor can better serve each process), and dynamic resource allocation (via a "use-as-needed" scheme where a process uses system resources such as memory only as needed). Mac OS X has three separate application areas, or environments:

Classic This area, formerly called the Blue Box, allows for the running of any Mac OS 8 application. If a program runs on Mac OS 8 now, then a software developer need make no changes to an existing program in order for it to run on Mac OS X. There is a key drawback to leaving Mac OS 8-compatible applications untouched, however. While such a program runs fine on a Mac hosting Mac OS X, it won't take advantage of the new features of Mac OS X (as mentioned in the above paragraph).

Carbon This area allows for the running of Mac OS 8-compatible applications that have been recompiled, or fine-tuned, for Mac OS X. Such a program does take advantage of the new features of Mac OS X. Such a program can also be run on Mac OS 8, though of course when it does it won't retain Mac OS X features such as enhanced performance (since the benefits of Mac OS X of course won't be present on the Mac OS 8 Macintosh).

Cocoa This environment, formerly referred to as Yellow Box, is for new programs that, like Carbon applications, take advantage of the new features of Mac OS X. A Cocoa application, however, won't run on a Mac hosting Mac OS 8 or 9.

The difference between a Classic application and either a Carbon or a Cocoa application are obvious - a classic application isn't upgraded to capitalize on the benefits of Mac OS X. The difference between a Carbon application and a Cocoa application aren't so obvious. To an end user the differences aren't noticeable at all. That's because the differences are found in the source code used to create both types of program. A Carbon application is built from code that uses the Carbon API - the modified Toolbox API. A Cocoa application is instead built from an entirely different API - one based on the NeXT OpenStep API. While a Carbon application is typically written in C or C++ (or possibly Java), a Cocoa application is typically written in Java or Objective-C. Because this column has for years featured the Macintosh Toolbox API (the only API there was for creating Mac programs sporting the Macintosh graphical user interface), we'll be focusing on Carbon. That way almost everything you've learned in previous Getting Started articles still applies to your future Carbon programming endeavors. More advanced programmers, or programmers familiar with NeXT's OpenStep API would be wise to learn Cocoa - it's tools (primarily Interface Builder, which let's you "draw" your application's user interface and add common functionality before you start writing code) aid in the rapid development of Mac OS X applications.

Converting to Carbon

Apple's goal in developing the Carbon API: to give programmers an easy means to make their existing applications ready for Mac OS X. By starting with the time-tested, and very familiar, Macintosh Toolbox, Apple knew that a programmer's learning curve would be minimized. When you look at the routines that make up the Carbon API you will notice that they look pretty much like the routines that make up the Macintosh Toolbox API. Carbon, it turns out, is simply a cleaned-up and enhanced Macintosh Toolbox. That's great news for those of us familiar with the Toolbox.

The Macintosh application model (event-driven, menu and window interface) is essentially unchanged in Carbon. Mac OS 8 (and now Mac OS 9) and Mac OS X are built on different cores, though, so how an application accesses system services does differ in some respects. To write an application using Carbon, or to Carbon-tune an existing application, there are a few issues you need to be aware of.

Separate Application Address Spaces

A chief advantage of Mac OS X is that each application runs in it's own protected address space. When one application crashes, other running applications remain unaffected. A Carbon application takes advantage of Mac OS X features, so a Carbon application runs in its own protected address space. If your application uses system memory or temporary memory, you'll need to make some changes. Simple applications, like the ones we've been writing here in Getting Started articles, don't take any liberties with memory, so this issue won't affect our (and perhaps, your) trivial programs.

If you're writing more complex applications, check your source code for use of the FreeMem(), PurgeMem(), and MaxMem() Toolbox functions. These routines are supported in Carbon, and will deliver expected results when your Carbonized program runs under Mac OS 8. But when that same program runs under Mac OS X, these routines do essentially nothing. You'll want to evaluate their use in your application to see if the tasks they are expected to accomplish are important under Mac OS X.

68K Code and the Mixed Mode Manager

When Apple made the transition from 68K to PowerPC processors, the concept of the universal procedure pointer (UPP) came about. A UPP is a pointer to a data structure that holds information about a function. One of the pieces of information specifies the instruction set architecture of the function. That is, whether the function can be handled directly by the PowerPC processor or whether the Mixed Mode Manager must pass instructions to a 68K emulator for preliminary processing. Mac OS X does not run 68K code, so the Mixed Mode Manager is of no use to an application running under Mac OS X. If your application includes the use of the Mixed Mode Manager, though, you shouldn't need to worry. Carbon supports UPPs transparently (meaning that you can still use UPPs so that your application runs properly on Mac OS 8).

Printing

If you application includes the ability to print, then you'll need to make changes to it - Carbon includes a new Printing Manager. By using the new Printing Manager your application will be able to print on Mac OS 8 using existing printer drivers and be able to print on Mac OS X using new printer drivers. Detailed coverage of the new Carbon Printing Manager is well beyond the scope of this article - but you can take a peek at this manager's functions and data types by looking at the header file PMApplication.h.

Callback functions

A callback routine is an application-defined function that the system executes when some task is completed. Back in this year's March Getting Started article we provided an example of a callback routine - we wrote one that the Sound Manager invoked to let our program know that a sound had completed playing. Carbon supports such application-defined callback routines, so the callback code of an application (such as our March example AsynchPlayer) will not need modification.

Carbon and Opaque Data Structures

Much of the Carbon API consists of Toolbox routines that have been made Mac OS X compatible. But Carbon also includes new routines as well. A big change brought on by Carbon is that many commonly used data structures are now opaque. That is, their internal structure - the fields or members that make up the structures - are hidden from the programmer. For instance, while a window still consists of a WindowRecord, your application should not attempt to directly access the fields of that record. The same holds true for dialog boxes, menus, controls, and the QuickDraw globals.

To allow your program to access opaque data, Carbon introduces new accessor functions. Here's an example. In the past, you could directly access a WindowRecord field by first casting a WindowPtr to a WindowPeek, and by then examining a field of the WindowRecord. If your program defined a few different types of windows, you could keep track of what type a window was by storing an application-defined constant in the windowKind field of the window's WindowRecord. Like this:

#define	kDrawingWindow		1
#define	kTextWindow			2
WindowPtr	theWindow;

theWindow = GetNewWindow( 128, nil, (WindowPtr)-1L );
(WindowPeek) theWindow->windowKind = kDrawingWindow;

The above snippet creates a new window and specifies that this window be considered to be a drawing window. Attempting to compile the above code using the Carbon API will result in errors. That's because Carbon won't let you access the opaque fields of the WindowRecord. Instead of using a WindowPeek, you'll use the new SetWindowKind() function:

theWindow = GetNewWindow( 128, nil, (WindowPtr)-1L );
SetWindowKind( theWindow, kDrawingWindow );

Carbon introduces a number of new routines to make life with opaque data structures manageable. You'll be seeing a lot more of them in future articles.

CodeWarrior and Carbon

Compiling your Carbon code and building an application results in an executable (a program) that can run on Mac OS 8 or 9, and can run on Mac OS X. You don't need to keep two separate sets of code, or build two applications. If you're fortunate enough to have a Mac running Mac OS X, you can do your work on that machine. If you have Mac OS 8 or 9, you can now also take care of business. This wasn't possible a while back because the tools for non-Mac OS X development didn't exist for Mac OS 8. Now they do - if you have a recent version of Metrowerks CodeWarrior, such as CodeWarrior 5.0..

CarbonLib Shared Library

To build a Carbon application you'll create a new CodeWarrior project based on CodeWarrior's Carbon stationary. Doing that results in a project that includes a Carbon Support folder which holds a number of files that may be unfamiliar to you. Figure 1 shows the project that results from the Carbon stationary. Note that if you're using an older version of CodeWarrior, you won't have the Carbon Support folder in your Metrowerks CodeWarrior folder.


Figure 1.A CodeWarrior project based on Carbon stationary.

Of key interest here is the CarbonLib and LiteCarbonLib shared library files. The CarbonLib shared library provides the Carbon functions that your project will be using. LiteCarbonLib holds a subset of the functions found in CarbonLib. Mac OS 8 does support all of the existing Carbon functions. As of this writing, Mac OS X doesn't include support for all of the Carbon functions. LiteCarbonLib holds only those functions currently supported by Mac OS X. If you want to build an application that is Carbon-compliant, and you don't need to test it under Mac OS X now, then your interested in CarbonLib. If you need to test your Carbon-compliant application on Mac OS X now, you'll want to build it with LiteCarbonLib to ensure that it will run on Mac OS X now. Once Mac OS X fully supports all the Carbon functions (remember, Mac OS X Client version for consumers isn't shipping as of this writing), this dual-library issue will disappear - we'll all only need the full set of functions found in CarbonLib.

Project Targets

The project target menu near the top left of the project window is used to determine what type, or types, of applications get built when you choose Run or Make from the Project menu. For Mac projects you've typically selected a 68K, PowerPC, or fat application. As shown in Figure 2, here in a Carbon project, you'll select a Mach-o, CarbonLib, or LiteCarbonLib application (or all of those types). Here's how you'll decide which target to select.

CarbonLib When you perform a build on a project (when you choose Run or Make from the Project menu), CodeWarrior creates an object file from each source file and then links these separate object files (along with the resources in project resource files) to form a single executable, or application. For Mac OS 8 application development, the resulting object files are in Code Fragment Manager (CFM) format. These code fragments are stored in Preferred Executable Format (PEF) containers and are managed by the Code Fragment Manager. CodeWarrior pretty much hides those details from you - so don't feel bad if acronyms such as CFM and PEF are new to you. Mac OS X supports the Code Fragment Manager, so this way of creating an application that runs on Mac OS X still works. In fact, if you're creating a Carbon application that is to be able to run on both Mac OS X and on Mac OS 8, you must create an application using CFM object files (otherwise the resulting application couldn't run on Mac OS 8). To tell CodeWarrior to generate a Carbon application that runs on both Mac OS 8 and Mac OS X, you'll choose the CarbonLib item from the project window's target pop-up menu. That's what's being selected in Figure 2 (there the menu item is named BasicApp CarbonLib because the CarbonLib item is prefaced with the project's name).

LiteCarbonLib If you're building the application on a Mac running Mac OS 8, and you may be soon testing the application on a machine running Mac OS X, you may want to instead use the LiteCarbonLib menu item (the last item in the menu shown in Figure 2). Recall that Mac OS X doesn't support all Carbon routines at this time, so creating a LiteCarbonLib application ensures that when you run the resulting application on Mac OS X it won't attempt to access unsupported routines. When Mac OS X fully supports Carbon, there'll be no need to build a LiteCarbonLib application.

Mach-o Mac OS X supports CFM object files and the Code Fragment Manager, and thus CarbonLib applications. But it also supports the Mach object file format, also referred to as Mach-o. Mac OS 8 doesn't support Mach-o, so you can only target Mach-o if your application is only meant to run on Mac OS X. A more likely reason to target Mach-o is for debugging purposes. At this time Mach-o is the best format for debugging an application on Mac OS X.

BuildAllTypes Hopefully this target type is self-explanatory - choosing it results in the building of all three types of executables.


Figure 2. Mac OS X/Carbon targets in CodeWarrior.

Source Code

If your application is a simple one, as many of our Getting Started examples are, you may be able to make its code Carbon-compatible very easily. In fact, just a few alterations to your code may do the trick. One addition you will need to make is the following line of code to the top (before any #includes) of one of your source files:

#define TARGET_CARBON 1

Other changes you need to make to your source code are dependent on just what your program does. In this article we've provided a few instances where you'll need to watch for Carbon-compatibility.

Testing For Carbon Compatibility

Back in January we discussed how you can easily test your code for Carbon compatibility. The steps for doing so remain essentially the same - you'll Carbon Date your code using Apple's Carbon Dater. A free download of this software program is available from Apple at <http://developer.apple.com/macosx/dater.html>.

To use the Carbon Dater software you simply drag and drop your program (not the source code, but rather the ready-to-run standalone application itself) onto the Carbon Dater application icon. Carbon Dater will launch, examine the application that was dropped on it, and generate an output file. This output file needs further analysis. Apple does that free, quickly (usually in less than an hour), and by an automated process if you e-mail the Carbon Dater output file (which ends with the extension .CCT) to CarbonDating@apple.com (note that Apple recommends that you send the .CCT file as a stuffed file).

In exchange for your submission of a .CCT file, Apple sends you a report in HTML format. Open the report in your favorite Web browser to see how Carbon-compatible your application is. Figure 3 shows a part of that report for a small application named BasicApp.


Figure 3. A Carbon report from Apple.

Apple examines the Carbon Dater output file in order to determine all of the Toolbox functions your code accesses, and to then tell you which calls you need to update or replace. Every objectionable, or questionable, Toolbox call your program makes appears listed in the report. After looking over the report you'll have an idea of how much work (or how much more work) is needed in order to make your application fully Carbon-compliant.

Till Next Month...

Apple is very well along in its job of creating the Carbon API - but the Carbon API is not yet finalized. When that time comes (and it will be soon), we'll have one more Carbon-related Getting Started column. In that article we'll look back at a previously written Getting Started example program, and look forward at what it takes to Carbonize it. We'll provide the complete source code listing - with detailed discussion - one just what changes are needed to get the program ready for Mac OS X and for Mac OS 8 and 9. Until then, we'll move on to other topics...

 
AAPL
$524.94
Apple Inc.
+5.93
MSFT
$40.01
Microsoft Corpora
-0.39
GOOG
$536.10
Google Inc.
-20.44

MacTech Search:
Community Search:

Software Updates via MacUpdate

VMware Fusion 6.0.3 - Run Windows apps a...
VMware Fusion allows you to create a Virtual Machine on your Mac and run Windows (including Windows 8.1) and Windows software on your Mac. Run your favorite Windows applications alongside Mac... Read more
Tweetbot 1.5.1 - Popular iOS twitter cli...
Tweetbot is a full-featured OS X Twitter client with a lot of personality. Whether it's the meticulously-crafted interface, sounds and animation, or features like multiple timelines and column views... Read more
Mac DVDRipper Pro 4.1.7 - Copy, backup,...
Mac DVDRipper Pro is the DVD backup solution that lets you protect your DVDs from scratches, save your batteries by reading your movies from your hard disk, manage your collection with just a few... Read more
PDFpenPro 6.2 - Advanced PDF toolkit for...
PDFpenPro allows users to edit PDF's easily. Add text, images and signatures. Fill out PDF forms. Merge or split PDF documents. Reorder and delete pages. Even correct text and edit graphics! Create... Read more
PDFpen 6.2 - Edit and annotate PDFs with...
PDFpen allows users to easily edit PDF's. Add text, images and signatures. Fill out PDF forms. Merge or split PDF documents. Reorder and delete pages. Even correct text and edit graphics! Features... Read more
Monolingual 1.5.9 - Remove unwanted OS X...
Monolingual is a program for removing unnecesary language resources from OS X, in order to reclaim several hundred megabytes of disk space. It requires a 64-bit capable Intel-based Mac and at least... Read more
Maya 2015 - Professional 3D modeling and...
Maya is an award-winning software and powerful, integrated 3D modeling, animation, visual effects, and rendering solution. Because Maya is based on an open architecture, all your work can be scripted... Read more
Starcraft II: Wings of Liberty 1.1.1.180...
Download the patch by launching the Starcraft II game and downloading it through the Battle.net connection within the app. Starcraft II: Wings of Liberty is a strategy game played in real-time. You... Read more
Sibelius 7.5.0 - Music notation solution...
Sibelius is the world's best-selling music notation software for Mac. It is as intuitive to use as a pen, yet so powerful that it does most things in less than the blink of an eye. The demo includes... Read more
Typinator 5.9 - Speedy and reliable text...
Typinator turbo-charges your typing productivity. Type a little. Typinator does the rest. We've all faced projects that require repetitive typing tasks. With Typinator, you can store commonly used... Read more

Latest Forum Discussions

See All

This Week at 148Apps: April 14-18, 2014
Spring Into Our App Reviews   | Read more »
Have a Special Dead Trigger 2 Easter Bas...
Have a Special Dead Trigger 2 Easter Basket Full of Goodies, Courtesy of Madfinger Games Posted by Rob Rich on April 18th, 2014 [ permalink ] Dead Trigger 2 | Read more »
Almost All of Playdek’s Library is on Sa...
Almost All of Playdek’s Library is on Sale Right Now, and You Should Check it Out Posted by Rob Rich on April 18th, 2014 [ permalink ] Playdek has released quite a few great iOS ports of board and card games over the years, and now most of them... | Read more »
Zynga Launches Brand New Farmville Exper...
Zynga Launches Brand New Farmville Experience with Farmville 2: Country Escape Posted by Tre Lawrence on April 18th, 2014 [ permalink ] | Read more »
David. Review
David. Review By Cata Modorcea on April 18th, 2014 Our Rating: :: MINIMALISTIC IN A DIFFERENT WAYUniversal App - Designed for iPhone and iPad David is a minimalistic game wrapped inside of a soothing atmosphere in which the hero... | Read more »
Eyefi Unveils New Eyefi Cloud Service Th...
Eyefi Unveils New Eyefi Cloud Service That Allows Users to Share Media Across Personal Devices Posted by Tre Lawrence on April 18th, 2014 [ permalink ] | Read more »
Tales from the Dragon Mountain: The Lair...
Tales from the Dragon Mountain: The Lair Review By Jennifer Allen on April 18th, 2014 Our Rating: :: STEADY ADVENTURINGiPad Only App - Designed for the iPad Treading a safe path, Tales from the Dragon Mountain: The Lair is a... | Read more »
Yahoo Updates Flickr App with Advanced E...
Yahoo Updates Flickr App with Advanced Editing Features and More Posted by Tre Lawrence on April 18th, 2014 [ permalink ] | Read more »
My Incredible Body - A Kid's App to...
My Incredible Body - A Kid's App to Learn about the Human Body 1.1.00 Device: iOS Universal Category: Education Price: $2.99, Version: 1.1.00 (iTunes) Description: Wouldn’t it be cool to look inside yourself and see what was going on... | Read more »
Trials Frontier Review
Trials Frontier Review By Carter Dotson on April 18th, 2014 Our Rating: :: A ROUGH LANDINGUniversal App - Designed for iPhone and iPad Trials Frontier finally brings the famed stunt racing franchise to mobile, but how much does its... | Read more »

Price Scanner via MacPrices.net

Android Leads in Operating System Share Andro...
Consumer Intelligence Research Partners, LLC (CIRP) has released its latest results of its research on mobile phone operating systems for the calendar quarter that ended March 31, 2014. This analysis... Read more
Pelican Products, Inc. Introduces New Lineup...
Pelican Products, Inc., the global leader in the design and manufacture of high-performance protective cases, today announced the launch of a new line of rugged phone cases for both the Apple iPhone... Read more
SaveDrives – Car Dashboard Video Camera &...
Drivers who want to help reduce potential damage to their health and finances in the event of an accident can download the innovative new no-cost app SaveDrives – Car Dashboard Video Camera &... Read more
Deal Alert! 13-inch MacBook Pro on sale for $...
Best Buy has the 13″ 2.5GHz MacBook Pro on sale for $999.99 on their online store. Choose free shipping or free instant local store pickup (if available). Their price is $200 off MSRP. Price is valid... Read more
Free HopTo 2.2 Helps Enhance Your Productivit...
The HopTo app helps you do more on your iPad by providing more and easier adaccess to files and documents. Version 2.2 adds Egnyte and HopTo’s Mac OSX File Connector. If you already have the hopTo... Read more
National Distracted Driving Awareness Month:...
As the country recognizes National Distracted Driving Awareness Month, Sprint is reminding wireless consumers to focus on driving while behind the wheel, to not text or email while driving, and to... Read more
13-inch 2.4GHz Retina MacBook Pro available f...
Abt has the 13″ 2.4GHz 128GB Retina MacBook Pro available for $1229 including free shipping. Their price is $70 off MSRP. Read more
iMacs on sale for up to $160 off MSRP this we...
Best Buy has iMacs on sale for up to $160 off MSRP for a limited time. Choose free home shipping or free instant local store pickup (if available). Prices are valid for online orders only, in-store... Read more
iPad Airs on sale this weekend for up to $100...
Best Buy has WiFi iPad Airs on sale for $50 off MSRP and WiFi + Cellular iPad Airs on sale for $100 off MSRP on their online store for a limited time, with prices now starting at $449. Choose free... Read more
Apple restocks refurbished Mac minis starting...
The Apple Store has restocked Apple Certified Refurbished Mac minis for up to $150 off the cost of new models. Apple’s one-year warranty is included with each mini, and shipping is free: - 2.5GHz Mac... Read more

Jobs Board

*Apple* Solutions Consultant (ASC) - Apple (...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
Position Opening at *Apple* - Apple (United...
…customers purchase our products, you're the one who helps them get more out of their new Apple technology. Your day in the Apple Store is filled with a range of Read more
*Apple* Solutions Consultant (ASC) - Apple (...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
*Apple* Inc. Research Data Specialist - Appl...
…of Worldwide Market Research & Intelligence. The team is responsible for conducting Apple branded consumer market research. It is also responsible for analyzing data Read more
*Apple* Automotive Parts Department position...
Apple Automotive is one of the fastest growing dealer…and it shows. Consider making the switch to the Apple Automotive Group today! At Apple Automotive, we Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.