TweetFollow Us on Twitter

A Simple Plug-In Example

Volume Number: 14 (1998)
Issue Number: 6
Column Tag: Plugging In

A Simple Plug-In Example

by Joe Zobkiw

How to add plug-in support to your application

If you've ever used Adobe Photoshop, HyperCard, or even the latest version of Metrowerks' CodeWarrior you've made use of plug-in technology. Plug-ins are simply executable code (and resources) that reside in a file other than that of the application itself. Applications can load plug-ins dynamically at run-time and benefit from the functionality they provide.

For example, Photoshop is a high-end graphics application that allows you to load an image and manipulate it in any of a number of interesting ways. You can add a drop-shadow, change the color balance, produce lighting effects, and more by using special. Much of this functionality is provided by plug-ins, known in this case as Photoshop Filters. When you launch the Photoshop application, it scans a folder in the same folder as itself named "Plug-ins" for files of a specific type. As it finds these files it makes their functionality available from within the program by displaying them in the Filters menu. Selecting items from this menu invoke the appropriate plug-in and extend the capabilities of Photoshop.

You might ask yourself, why would anyone want to write dozens of separate plug-ins if they are just going to be used from within an application anyway? The reasons are simple. By extracting certain functionality into plug-ins, you can easily update or add new features to an application without changing the application itself. For instance, to add a new filter to Photoshop, you simply drag it into the Plug-ins folder and relaunch the application. This not only allows Adobe to easily manage their software, but it also allows hundreds of third-party developers to enhance and customize the Photoshop application by writing Photoshop Filters to the Adobe-published specification, all without having access to the source code of Photoshop itself.

Given these examples, you can see that using plug-ins can not only help ease the burden of development, but it can also help your salespeople by making your application more accessible, more customizable, and more appealing to your customers. Let's look at an example of how you might implement plug-in support in your application.

Basic Plug-in Support

The following example shows you the most basic steps required to implement plug-in support in an application. We have implemented a simple PowerPC application that loads a special plug-in, in our case compiled as a PowerPC shared library, and executes code within it. Once you understand how this application and plug-in work together, you can easily extend the sample and devise your own plug-in architecture for your application.

Figure 1.

For this project we are using CodeWarrior Professional Release 2. Our shared library is written in C and our application is C++. We started out by creating a single project file that contains both targets for this project, the application and the shared library. The project is set up so whenever we build the application, the shared library will be brought up to date if need be. You do not need to have both of your targets in the same project file. However, CodeWarrior Professional Release 2 allows us to do this and it makes it easier for this particular project.

Figure 2.

Before you design an application to call a plug-in you must decide on the calling conventions. In this simple case we have decided to implement a single function in our shared library that will be called from the application. We are calling our function DisplayDialogAndBeep. It is called with one parameter, inBeepTimes, which represents the number of times to make the computer beep while displaying a dialog. It is defined as follows:

Listing 1.

OSErr DisplayDialogAndBeep(long inBeepTimes);

When the project builds both the application and the shared library, it produces two files. One is an application program named "Application" and the other is a shared library named "Shared Library." When the application is launched, it prompts the user to enter a value for inBeepTimes. Upon entering this value, the application attempts to open the shared library by name, find the exported DisplayDialogAndBeep function by name, and call the function. If these steps are completed successfully, the computer will beep and you will see a dialog box as follows:

Figure 3.

Let's look at the shared library to see how it is created, then we can see how the application is used to call this code. First, it is important to understand that a shared library is simply a file that contains a code fragment (PowerPC code) in the data fork. If you are not familiar with code fragments and the Code Fragment Manager, you will want to read about them in Inside Macintosh. You can do so at http://devworld.apple.com/.

The compiler handles most of the details for you but you want to make sure that your project is set up to export (at a minimum) the functions that you expect to be able to call from your application. If the functions are not exported, your application will not be able to access them. Other than that, a shared library is not much more than a bunch of functions without a required main() entry point as you are used to seeing in applications.

Another interested and useful feature of shared libraries (and any code fragment for that matter) is the ability to include a start function, similar to main(), the main entry point of the code fragment. You can also include initialization and termination functions. These are called when the code fragment is first connected to and when the connection is closed, respectively. Our plug-in makes use of the initialization and termination functions to insure that our shared library resource file is available so we can access our dialog box.

You do not need to use the initialization and termination routines in this way. In fact, you can use them in any way you choose, or not at all. I simply found it convenient to locate the plug-in file given the CFragInitBlockPtr that is passed into the initialization routine in this case.

The required code of the shared library, sans comments, is as follows:

Listing 2

#include <CodeFragments.h>
#include <MixedMode.h>
#include <ConditionalMacros.h>
#include <Sound.h>
#include "Shared Library.h"

enum {
   uppDisplayDialogAndBeepProcInfo = kCStackBased
       | RESULT_SIZE(SIZE_CODE(sizeof(OSErr)))
       | STACK_ROUTINE_PARAMETER(1, SIZE_CODE(sizeof(long)))
};

short   gFileRefNum;

__initialize

OSErr __initialize(CFragInitBlockPtr ibp)
{
   OSErr   err = noErr;

   gFileRefNum = -1;
   
   if (ibp->fragLocator.where == kDataForkCFragLocator) {
      gFileRefNum = 
         FSpOpenResFile(ibp->fragLocator.u.onDisk.fileSpec, 
                              fsRdPerm);
      if (gFileRefNum == -1)
         err = ResError();
   }
   
   return err;
}

__terminate

void __terminate(void)
{
   if (gFileRefNum != -1)
      CloseResFile(gFileRefNum);
}

DisplayDialogAndBeep

OSErr DisplayDialogAndBeep(long inBeepTimes)
{
   DialogPtr       d;
   Str32         sBeepTimes;
   long         i;
   unsigned long   someticks;
   short         saveResFile;
   saveResFile = CurResFile();
   UseResFile(gFileRefNum);
   NumToString(inBeepTimes, sBeepTimes);
   ParamText(sBeepTimes, "\p", "\p", "\p");
   d = GetNewDialog(256, nil, (WindowPtr)-1);
   if (d) {
      ShowWindow(d);
      DrawDialog(d);
   }
   
   for (i = 0; i < inBeepTimes; ++i) {
      FlashMenuBar(0);
      SysBeep(0);
      Delay(15, &someticks);
      FlashMenuBar(0);
      Delay(15, &someticks);
   }
   
   if (d)
      DisposeDialog(d);
      UseResFile(saveResFile);
      return noErr;
}

That's all there is to it, believe it or not.

The shared library isn't too useful on its own. It needs the application to call it in order for it to do anything. Basically the application first needs to locate the shared library by name. We call GetSharedLibrary() in order to do this. By passing in the name of the shared library we are looking for, the Code Fragment Manager will automatically look in the same folder as our application first, then proceed to look in the Extensions folder and the System folder until it either finds a shared library with the correct name or it fails. If found, GetSharedLibrary() will automatically open a connection (and execute its initialization routine mentioned earlier) to the shared library.

Once we find the shared library and connect to it we can then query it for an exported symbol named DisplayDialogAndBeep. In this case the symbol is an exported function but it might also be exported data. If found, we can continue by creating a routine descriptor for the function by calling NewRoutineDescriptor(), calling it by using CallUniversalProc(), and ultimately disposing of the routine descriptor using DisposeRoutineDescriptor().

Another way to call your shared library (or any code fragment for that matter) is by means of a main entry point, sometimes simply called main(). Under the 680x0 architecture that was the only way to communicate with a code resource. The code resource had a main entry point that you would call using a selector-based mechanism. That is, the main entry point would expect a selector (a unique identifier) to distinguish the purpose of the call, and then extra data, possibly in another parameter, to act on during that call. This technique allows the caller to not need to know specific exported function names, it can simply call through the main entry point, passing the correct selector and data. A sample main entry point might look like this:

OSErr main(long inSelector, void* ioDataPtr);

Another might use a single parameter block for all of the data, including the selector itself.

OSErr main(MyParameterBlock* ioParamPtr);

During the call to CallUniversalProc() is when the DisplayDialogAndBeep() function in the shared library will be called. It will be passed the parameters we specified, perform its duty, and return a result code. If you specify the universal procedure pointer incorrectly you will undoubtedly crash your computer during this call.

You can find more information about universal procedure pointers and routine descriptors in the Inside Macintosh chapter on the Mixed Mode Manager at http://devworld.apple.com/.

Once the call returns, the connection to the shared library is closed by calling CloseConnection(). At this time is when the termination routine in the shared library is executed.

The required code of the application, sans comments, is as follows:

Listing 3

ExecuteSharedLib
OSErr ExecuteSharedLib(long inBeepTimes)
{
   OSErr                     err = noErr, err2 = noErr;
   CFragConnectionID   connID = 0;
   Ptr                        mainAddr = nil;
   Str255                   errName;
   
   err = GetSharedLibrary("\pShared Library", 
                                    kPowerPCCFragArch, 
                                    kPrivateCFragCopy, 
                                    &connID, &mainAddr, errName);
   if (err == noErr) {
      Ptr         symAddr = nil;
      CFragSymbolClass   symClass;
      
      err = FindSymbol(connID, "\pDisplayDialogAndBeep", 
                              &symAddr, &symClass);
      if (err == noErr) {
         
         UniversalProcPtr upp =          
            NewRoutineDescriptor((ProcPtr)symAddr, 
            uppDisplayDialogAndBeepProcInfo, GetCurrentISA());
         if (upp) {
            err = CallUniversalProc(upp,    
                                       uppDisplayDialogAndBeepProcInfo, 
                                       inBeepTimes);
            DisposeRoutineDescriptor(upp);
         } else err = memFullErr;
      }
      
      err2 = CloseConnection(&connID);
      if (err == noErr) err = err2;
   }
   
   return err;
}

That's all there is to that too, believe it or not.

Enhanced Plug-in Support

Plug-ins Folder

The above example assumes your application knows the name of the plug-in before it is launched. However, in order to implement a Photoshop-style approach to plug-ins you need to be able to search for the plug-ins at run-time. This can be achieved using a very useful source code library called MoreFiles by Jim Luther.

MoreFiles allows you to (amongst numerous other features) easily scan a folder for files and call a specific function as files are found. Using this technique you can quickly locate all plug-ins that your application can use and add their names to a menu for your user to invoke as needed. MoreFiles can be downloaded from the Internet at ftp://dev.apple.com/devworld/Sample_Code/Files/ or http://members.aol.com/jumplong/.

Figure 4.

Callbacks

Something else to try is exporting functions from your application and having your plug-in call them, just as the application calls the functions in the plug-in. These are called callback functions because the plug-in is "calling back" into the application. These types of functions can be very useful in providing information to the plug-in as it is needed. For example, the plug-in can query the application to see if it has enough memory available in an internal buffer to handle a specific task before setting off on the task.

Import Libraries

You can also compile your shared library in the form of an import library. By doing this you can simply include the library in your project much like you would InterfaceLib. This way, you can easily call the exported functions in the import library without having to worry about the details of locating the library file, locating the exported function itself, and creating a universal procedure pointer. This may defeat the purpose of considering plug-ins in the first place, since the library is "linked" to your project. Another option, however, is to use the "weak link" option. Weak linking meets you in the middle of creating a full-fledged plug-in and "strong" linking to a library as described earlier. See your development environment documentation for details.

Fat Plug-ins

Calling a plug-in fat simply means that it can run natively on more than one microprocessor. A fat plug-in might contain code for both 680x0 and PowerPC microprocessors within the same file. This allows users to install just one file on any Macintosh computer and obtain the benefits of optimized code for their specific computer. You can easily compile and merge both 680x0 and PowerPC code in this manner. An informative book written on the subject (if I do say so myself) covers this in great detail. You can learn more about this technique (and other techniques mentioned in this article) from A Fragment of Your Imagination at http://www.triplesoft.com/fragment/.

What About SOM?

SOM is IBM's System Object Model. It was originally introduced on the Macintosh with OpenDoc. Although OpenDoc has moved on, SOM has stuck around. The Mac OS 8 Contextual Menu Manager uses SOM, for example. SOM allows you to use object-oriented techniques in a shared library. You garner all of the advantages of being able to create and override classes (including special SOM base classes) with the advantages of coding a shared library. Depending on your needs, SOM may be something you will want to explore.

For more information on SOM, see the February 1998 issue of MacTech magazine which contains articles on SOM and the Contextual Menu Manager. You can also find information on Apple's developer web site at http://devworld.apple.com/.

What About COM?

COM is Microsoft's Component Object Model. It is a programming model that defines how objects can communicate with one another, similar but different to SOM. ActiveX controls (previously known as OLE controls) are based on COM. For more information on COM and ActiveX read the June 1997 issue of MacTech Magazine.

Conclusion

Once you understand the basic concepts described in this article, you will begin to find new uses for plug-ins in your application. Many applications have areas that can be logically broken out into a plug-in architecture. The key is to understand and then experiment. Don't use this approach if you don't need it, but if you do, you can easily add years of life to your application by opening it up to yourself and third-party developers in this way. I look forward to hearing about how you've used this introductory plug-in architecture.

Special Thanks

Special thanks goes to our technical reviewers: Tantek Celik, Nick DeMello, Eric Gundrum and Marty Wachter.


Joe Zobkiw, zobkiw@triplesoft.com, is a programmer, author, musician and practicing carver of stone. He is the author of A Fragment of Your Imagination, a book about code fragments and code resources for the Mac OS. You can learn more about (and order a copy of) the book at http://www.triplesoft.com/fragment/.

 
AAPL
$103.30
Apple Inc.
+0.80
MSFT
$45.09
Microsoft Corpora
-0.34
GOOG
$577.33
Google Inc.
+5.73

MacTech Search:
Community Search:

Software Updates via MacUpdate

TextSoap 7.4.0 - Flexible text editing u...
TextSoap is for people who work with text. TextSoap effortlessly cleans up text from endlessly different formats. Wash away unwanted characters, spaces, tabs. Fix paragraphs with hard returns at the... Read more
NetShade 6.0.2 - Browse privately using...
NetShade is an Internet security tool that conceals your IP address on the web. NetShade routes your Web connection through either a public anonymous proxy server, or one of NetShade's own dedicated... Read more
Mac DVDRipper Pro 5.0 - Copy, backup, an...
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
pwSafe 3.1 - Secure password management...
pwSafe provides simple and secure password management across devices and computers. pwSafe uses iCloud to keep your password databases backed-up and synced between Macs and iOS devices. It is... Read more
StatsBar 1.8 - 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
Path Finder 6.5.5 - Powerful, award-winn...
Path Finder is a file browser that combines the familiar Finder interface with the powerful utilities and innovative features. Just a small selection of the Path Finder 6 feature set: Dual pane... Read more
QuarkXPress 10.2.1 - Desktop publishing...
With QuarkXPress, you can communicate in all the ways you need to -- and always look professional -- in print and digital media, all in a single tool. Features include: Easy to Use -- QuarkXPress is... Read more
Skype 6.19.0.450 - Voice-over-internet p...
Skype allows you to talk to friends, family and co-workers across the Internet without the inconvenience of long distance telephone charges. Using peer-to-peer data transmission technology, Skype... Read more
VueScan 9.4.41 - Scanner software with a...
VueScan is a scanning program that works with most high-quality flatbed and film scanners to produce scans that have excellent color fidelity and color balance. VueScan is easy to use, and has... Read more
Cloud 3.0.0 - File sharing from your men...
Cloud is simple file sharing for the Mac. Drag a file from your Mac to the CloudApp icon in the menubar and we take care of the rest. A link to the file will automatically be copied to your clipboard... Read more

Latest Forum Discussions

See All

Modern Combat 5 Gets a Major Multiplayer...
Modern Combat 5 Gets a Major Multiplayer Update Posted by Jessica Fisher on September 2nd, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
Alien Creeps TD Review
Alien Creeps TD Review By Jennifer Allen on September 2nd, 2014 Our Rating: :: EXPENSIVE DEFENSESUniversal App - Designed for iPhone and iPad Alien Creeps TD would be a fun if unremarkable Tower Defense game, but its heavy focus on... | Read more »
The Journey Down: Chapter Two Review
The Journey Down: Chapter Two Review By Jennifer Allen on September 2nd, 2014 Our Rating: :: DARK YET ENTICINGUniversal App - Designed for iPhone and iPad It’s a little dark, in every sense of the word, but The Journey Down:... | Read more »
Function Space, a Social Network App for...
Function Space, a Social Network App for Science, Launches on iOS Posted by Ellis Spice on September 2nd, 2014 [ permalink ] | Read more »
Stupidfast – How Taylor Martinez Switche...
How do you make an Endless Running game more than just another Endless Running game? By adding real life prizes to it, of course! That’s the thinking behind StupidFast: a game designed for football enthusiasts, and the brainchild of former college... | Read more »
Little Raiders: Robin’s Revenge Review
Little Raiders: Robin’s Revenge Review By Jennifer Allen on September 2nd, 2014 Our Rating: :: CASUAL RAIDINGUniversal App - Designed for iPhone and iPad Combining simple combat with village building is a potent combination for... | Read more »
Treasure Tombs: Ra Deal Coming from Bulk...
Treasure Tombs: Ra Deal Coming from Bulkypix and Dark Tonic This Fall Posted by Jessica Fisher on September 2nd, 2014 [ permalink ] Dark Tonic and | Read more »
Pirate Bash Review
Pirate Bash Review By Nadia Oxford on September 2nd, 2014 Our Rating: :: BAD PIRATES, GOOD TIMESUniversal App - Designed for iPhone and iPad Pirate Bash’s turn-based battles add an intriguing twist to a typical physics game.   | Read more »
Tiny Tower Vegas Review
Tiny Tower Vegas Review By Jennifer Allen on September 2nd, 2014 Our Rating: :: STEADY DEVELOPMENTUniversal App - Designed for iPhone and iPad Build a huge tower again but Vegas-style in Tiny Tower Vegas.   | Read more »
The Manhattan Project Review
The Manhattan Project Review By Andrew Fisher on September 2nd, 2014 Our Rating: :: ROCKET SCIENCEUniversal App - Designed for iPhone and iPad The Manhattan Project offers a great Euro-style gameplay experience, but it is totally... | Read more »

Price Scanner via MacPrices.net

Apple refurbished iPads available for up to $...
Apple is offering Certified Refurbished iPad Airs for up to $140 off MSRP. Apple’s one-year warranty is included with each model, and shipping is free. Stock tends to come and go with some of these... Read more
Are We Now In The Post-Post-PC Era?
A longtime and thoroughgoing laptop aficionado, I was more than a little dismayed by Steve Jobs’s declaration back in 2010 when he sprang the iPad on an unsuspecting world. that we’d entered a “post-... Read more
PC Outlook Improves, But 2014 Shipments Still...
According to the International Data Corporation (IDC) Worldwide Quarterly PC Tracker, worldwide PC shipments are expected to fall by -3.7 percent in 2014. To hat’s actually an improvement from the... Read more
IDC Lowers Tablet Sales Projections for 2014...
Following a second consecutive quarter of softer than expected demand, International Data Corporation (IDC) has lowered its worldwide tablet plus 2-in-1 forecast for 2014 to 233.1 million units. The... Read more
Apple now offering refurbished 21-inch 1.4GHz...
The Apple Store is now offering Apple Certified Refurbished 21″ 1.4GHz iMacs for $929 including free shipping plus Apple’s standard one-year warranty. Their price is $170 off the cost of new models,... Read more
Save $50 on the 2.5GHz Mac mini, on sale for...
B&H Photo has the 2.5GHz Mac mini on sale for $549.99 including free shipping. That’s $50 off MSRP, and B&H will also include a free copy of Parallels Desktop software. NY sales tax only. Read more
Save up to $300 on an iMac with Apple refurbi...
The Apple Store has Apple Certified Refurbished iMacs available for up to $300 off the cost of new models. Apple’s one-year warranty is standard, and shipping is free. These are the best prices on... Read more
The Rise of Phablets
Carlisle & Gallagher Consulting Group, a businesses and technology consulting firm focused solely on the financial services industry, has released an infographic depicting the convergence of... Read more
Bad Driver Database App Allows Good Drivers t...
Bad Driver Database 1.4 by Facile Group is a new iOS and Android app that lets users instantly input and see how many times a careless, reckless or just plain stupid driver has been added to the... Read more
Eddy – Cloud Music Player for iPhone/iPad Fre...
Ukraine based CapableBits announces the release of Eddy, its tiny, but smart and powerful cloud music player for iPhone and iPad that allows users to stream or download music directly from cloud... 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* 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* 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* 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
Senior Event Manager, *Apple* Retail Market...
…This senior level position is responsible for leading and imagining the Apple Retail Team's global event strategy. Delivering an overarching brand story; in-store, Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.