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
$118.63
Apple Inc.
+2.16
MSFT
$47.59
Microsoft Corpora
-0.39
GOOG
$539.27
Google Inc.
+1.77

MacTech Search:
Community Search:

Software Updates via MacUpdate

Carbon Copy Cloner 4.0.3 - Easy-to-use b...
Carbon Copy Cloner backups are better than ordinary backups. Suppose the unthinkable happens while you're under deadline to finish a project: your Mac is unresponsive and all you hear is an ominous,... Read more
ForeverSave 2.1.3 - Universal auto-save...
ForeverSave auto-saves all documents you're working on while simultaneously doing backup versioning in the background. Lost data can be quickly restored at any time. Losing data, caused by... Read more
Voila 3.8.1 - Capture, annotate, organiz...
Voila is a screen-capture, recording, and annotation tool that is a full-featured replacement for Mac's screen-capture and screen-recording capabilities. It has a large and robust set of editing,... Read more
SyncTwoFolders 2.0.6 - Syncs two user-sp...
SyncTwoFolders simply synchronizes two folders. It supports synchronization across mounted network drives and it is a possibility to run a simulation showing in a log what will be done. Please visit... Read more
Duplicate Annihilator 5.1.1 - Find and d...
Duplicate Annihilator takes on the time-consuming task of comparing the images in your iPhoto library using effective algorithms to make sure that no duplicate escapes. Duplicate Annihilator detects... Read more
Cobook 3.0.7 - Intelligent address book....
Cobook Contacts is an intuitive, engaging address book. Solve the problem of contact management with Cobook Contacts and its simple interface and powerful syncing and integration possibilities.... Read more
StatsBar 1.9 - Monitor system processes...
StatsBar gives you a comprehensive and detailed analysis of the following areas of your Mac: CPU usage Memory usage Disk usage Network and bandwidth usage Battery power and health (MacBooks only)... Read more
Cyberduck 4.6 - FTP and SFTP browser. (F...
Cyberduck is a robust FTP/FTP-TLS/SFTP browser for the Mac whose lack of visual clutter and cleverly intuitive features make it easy to use. Support for external editors and system technologies such... 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
Evernote 6.0.1 - Create searchable notes...
Evernote allows you to easily capture information in any environment using whatever device or platform you find most convenient, and makes this information accessible and searchable at anytime, from... Read more

Latest Forum Discussions

See All

This Week at 148Apps: November 17-21, 20...
Expert App Reviewers   So little time and so very many apps. What’s a poor iPhone/iPad lover to do? Fortunately, 148Apps is here to give you the rundown on the latest and greatest releases. And we even have a tremendous back catalog of reviews; just... | Read more »
RuPaul’s Drag Race: Dragopolis 2.0 is C...
RuPaul’s Drag Race: Dragopolis 2.0 is Coming to iOS December 4th Posted by Jessica Fisher on November 24th, 2014 [ permalink ] So Much Drama | Read more »
Crimson Keyboard (Utilities)
Crimson Keyboard 1.0 Device: iOS iPhone Category: Utilities Price: $1.99, Version: 1.0 (iTunes) Description: Introducing a faster way to type. Crimson Keyboard adapts to your writing style and provides smart, personal and contextual... | Read more »
The Sandbox EDU Review
The Sandbox EDU Review By Nadia Oxford on November 24th, 2014 Our Rating: :: COME PLAY IN THE SANDBOX AGAINUniversal App - Designed for iPhone and iPad Like its predecessor, The Sandbox EDU offers lots for players to see, do, and... | Read more »
Taichi Panda Hits iOS in December
Taichi Panda Hits iOS in December Posted by Jessica Fisher on November 24th, 2014 [ permalink ] Snail Games has released the first official game play trailer for  | Read more »
Five Apps to Make Your Thanksgiving Plan...
Thanksgiving is nearly upon us! You know what that means? Eating too much turkey, watching the Big Game, and spending time with family (whether you like it or not). Oh, and that scary Black Friday thing, but we won’t talk about that here. For those... | Read more »
Kingdom Rush Origins HD Review
Kingdom Rush Origins HD Review By Jennifer Allen on November 24th, 2014 Our Rating: :: JUST AS GOOD AS BEFOREiPad Only App - Designed for the iPad It’s more of the same again, but that’s really no bad thing at all.   | Read more »
Skylanders, Show Off How You Fight Kaos...
Skylanders, Show Off How You Fight Kaos to Win Cool Prizes Posted by Jessica Fisher on November 24th, 2014 [ permalink ] iPad Only App - Designed for the iPad | Read more »
Mark of the Dragon – Tips, Tricks, and S...
Calling All Dragon Riders: | Read more »
Crossy Road Review
Crossy Road Review By Jennifer Allen on November 24th, 2014 Our Rating: :: ADDICTIVELY FROGGER LIKEUniversal App - Designed for iPhone and iPad Frogger-like in nature, Crossy Road is an easy to recommend endless runner of sorts.   | Read more »

Price Scanner via MacPrices.net

Jumptuit Launches One-Tap Windows 8.1 iTunes...
Jumptuit has launched Windows 8.1 support for One-Tap iTunes Sync. with which Windows 8.1 users can now easily sync their iTunes libraries with Microsoft OneDrive. Jumptuit provides easy access from... Read more
CEA Study Finds More People Recycling Electro...
A new study by the Consumer Electronics Association (CEA) finds that electronics recycling receives the continued and growing support of consumers. According to the CEA,s Recycling and Reuse Study,... Read more
15″ 2.2GHz Retina MacBook Pro on sale for $17...
 B&H Photo has the 2014 15″ 2.2GHz Retina MacBook Pro on sale today for $1749. Shipping is free, and B&H charges NY sales tax only. B&H will also include free copies of Parallels Desktop... Read more
27-inch 3.5GHz 5K iMac in stock today and on...
 B&H Photo has the new 27″ 3.5GHz 5K iMac in stock today and on sale for $2299 including free shipping plus NY sales tax only. Their price is $200 off MSRP, and it’s the lowest price available... Read more
21-inch 1.4GHz iMac on sale for $979, save $1...
B&H Photo has the new 21″ 1.4GHz iMac on sale for $979.99 including free shipping plus NY sales tax only. Their price is $120 off MSRP. B&H will also include free copies of Parallels Desktop... Read more
13-inch 1.4GHz/256GB MacBook Air on sale for...
B&H Photo has lowered their price on the 13″ 1.4GHz/256GB MacBook Air to $1059.99 including free shipping plus NY sales tax only. Their price is $140 off MSRP, and it’s the lowest price for this... Read more
Save up to $400 with Apple refurbished 2014 1...
The Apple Store has restocked Apple Certified Refurbished 2014 15″ Retina MacBook Pros for up to $400 off the cost of new models. An Apple one-year warranty is included with each model, and shipping... Read more
New 13-inch 1.4GHz MacBook Air on sale for $8...
 Adorama has the 2014 13″ 1.4GHz/128GB MacBook Air on sale for $899.99 including free shipping plus NY & NJ tax only. Their price is $100 off MSRP. B&H Photo has the 13″ 1.4GHz/128GB MacBook... Read more
Apple Expected to Reverse Nine-Month Tablet S...
Apple and Samsung combined accounted for 62 percent of the nearly 36 million branded tablets shipped in 3Q 2014, according to early vendor shipment share estimates from market intelligence firm ABI... Read more
Stratos: 30 Percent of US Smartphone Owners t...
Stratos, Inc., creator of the Bluetooth Connected Card Platform, has announced results from its 2014 Holiday Mobile Payments Survey. The consumer survey found that nearly one out of three (30 percent... Read more

Jobs Board

*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the 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* 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* Solutions Consultant (ASC)- Retail S...
**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
Project Manager, *Apple* Financial Services...
**Job Summary** Apple Financial Services (AFS) offers consumers, businesses and educational institutions ways to finance Apple purchases. We work with national and Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.