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...

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Ride into the zombie apocalypse in style...
Back in the good old days of Flash games, there were a few staples; Happy Wheels, Stick RPG, and of course the apocalyptic driver Earn to Die. Fans of the running over zombies simulator can rejoice, as the sequel to the legendary game, Earn to Die... | Read more »
Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »
Netflix Games expands its catalogue with...
It is a good time to be a Netflix subscriber this month. I presume there's a good show or two, but we are, of course, talking about their gaming service that seems to be picking up steam lately. May is adding five new titles, and there are some... | Read more »
Pokemon Go takes a step closer to real P...
When Pokemon Go was first announced, one of the best concepts of the whole thing was having your favourite Pokemon follow you in the real world and be able to interact with them. To be frank, the AR Snapshot tool could have done a lot more to help... | Read more »
Seven Knights Idle Adventure drafts in a...
Seven Knights Idle Adventure is opening up more stages, passing the 15k mark, and players may find themselves in need of more help to clear these higher stages. Well, the cavalry has arrived with the introduction of the Legendary Hero Iris, as... | Read more »
AFK Arena celebrates five years of 100 m...
Lilith Games is quite the behemoth when it comes to mobile games, with Rise of Kingdom and Dislyte firmly planting them as a bit name. Also up there is AFK Arena, which is celebrating a double whammy of its 5th anniversary, as well as blazing past... | Read more »
Fallout Shelter pulls in ten times its u...
When the Fallout TV series was announced I, like I assume many others, assumed it was going to be an utter pile of garbage. Well, as we now know that couldn't be further from the truth. It was a smash hit, and this success has of course given the... | Read more »
Recruit two powerful-sounding students t...
I am a fan of anime, and I hear about a lot that comes through, but one that escaped my attention until now is A Certain Scientific Railgun T, and that name is very enticing. If it's new to you too, then players of Blue Archive can get a hands-on... | Read more »
Top Hat Studios unveils a new gameplay t...
There are a lot of big games coming that you might be excited about, but one of those I am most interested in is Athenian Rhapsody because it looks delightfully silly. The developers behind this project, the rather fancy-sounding Top Hat Studios,... | Read more »
Bound through time on the hunt for sneak...
Have you ever sat down and wondered what would happen if Dr Who and Sherlock Holmes went on an adventure? Well, besides probably being the best mash-up of English fiction, you'd get the Hidden Through Time series, and now Rogueside has announced... | Read more »

Price Scanner via MacPrices.net

Apple Studio Display with Standard Glass on s...
Best Buy has the standard-glass Apple Studio Display on sale for $300 off MSRP for a limited time. Their price is the lowest available for a Studio Display among Apple’s retailers. Shipping is free... Read more
AirPods Max headphones back on sale for $449,...
Amazon has Apple AirPods Max headphones in stock and on sale for $100 off MSRP, only $449. The sale price is valid for all colors at the time of this post. Shipping is free: – AirPods Max: $449.99 $... Read more
Deal Alert! 13-inch M2 MacBook Airs on record...
Amazon has 13″ MacBook Airs with M2 CPUs in stock and on sale this week for only $829 in Space Gray, Silver, Starlight, and Midnight colors. Their price is $170 off Apple’s MSRP, and it’s the lowest... Read more
Apple Watch Ultra 2 on sale for $50 off MSRP
Best Buy is offering Apple Watch Ultra 2 models for $50 off MSRP on their online store this week. Sale prices available for online orders only, in-store prices may vary. Order online, and choose free... Read more
Apple introduces the new M4-powered 11-inch a...
Today, Apple revealed the new 2024 M4 iPad Pro series, boasting a surprisingly thin and light design that pushes the boundaries of portability and performance. Offered in silver and space black... Read more
Apple introduces the new 2024 11-inch and 13-...
Apple has unveiled the revamped 11-inch and brand-new 13-inch iPad Air models, upgraded with the M2 chip. Marking the first time it’s offered in two sizes, the 11-inch iPad Air retains its super-... Read more
Apple discontinues 9th-gen iPad, drops prices...
With today’s introduction of the new 2024 iPad Airs and iPad Pros, Apple has (finally) discontinued the older 9th-generation iPad with a home button. In response, they also dropped prices on 10th-... Read more
Apple AirPods on sale for record-low prices t...
Best Buy has Apple AirPods on sale for record-low prices today starting at only $79. Buy online and choose free shipping or free local store pickup (if available). Sale price for online orders only,... Read more
13-inch M3 MacBook Airs on sale for $100 off...
Best Buy has Apple 13″ MacBook Airs with M3 CPUs in stock and on sale today for $100 off MSRP. Prices start at $999. Their prices, along with Amazon’s, are the lowest currently available for new 13″... Read more
Amazon is offering a $100 discount on every 1...
Amazon has every configuration and color of Apple’s 13″ M3 MacBook Air on sale for $100 off MSRP, now starting at $999 shipped. Shipping is free: – 13″ MacBook Air (8GB RAM/256GB SSD): $999 $100 off... Read more

Jobs Board

*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
Relationship Banker *Apple* Valley Main - W...
…Alcohol Policy to learn more. **Company:** WELLS FARGO BANK **Req Number:** R-367184 **Updated:** Wed May 08 00:00:00 UTC 2024 **Location:** APPLE VALLEY,California Read more
Rehabilitation Technician - *Apple* Hill (O...
Rehabilitation Technician - Apple Hill (Outpatient Clinic) - PRN Location: York Hospital, York, PA Schedule: PRN/Per Diem Sign-On Bonus Eligible Remote/Hybrid Read more
LPN-Physician Office Nurse - Orthopedics- *Ap...
LPN-Physician Office Nurse - Orthopedics- Apple Hill Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Read more
Medical Assistant Lead - Orthopedics *Apple*...
Medical Assistant Lead - Orthopedics Apple Hill Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Now Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.