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

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »
Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »

Price Scanner via MacPrices.net

New today at Apple: Series 9 Watches availabl...
Apple is now offering Certified Refurbished Apple Watch Series 9 models on their online store for up to $80 off MSRP, starting at $339. Each Watch includes Apple’s standard one-year warranty, a new... Read more
The latest Apple iPhone deals from wireless c...
We’ve updated our iPhone Price Tracker with the latest carrier deals on Apple’s iPhone 15 family of smartphones as well as previous models including the iPhone 14, 13, 12, 11, and SE. Use our price... Read more
Boost Mobile will sell you an iPhone 11 for $...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering an iPhone 11 for $149.99 when purchased with their $40 Unlimited service plan (12GB of premium data). No trade-in is required... Read more
Free iPhone 15 plus Unlimited service for $60...
Boost Infinite, part of MVNO Boost Mobile using AT&T and T-Mobile’s networks, is offering a free 128GB iPhone 15 for $60 per month including their Unlimited service plan (30GB of premium data).... Read more
$300 off any new iPhone with service at Red P...
Red Pocket Mobile has new Apple iPhones on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide MVNO using all the major wireless carrier... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, available for $759 for 8-Core CPU/7-Core GPU/256GB models and $929 for 8-Core CPU/8-Core GPU/512GB models. Apple’s one-year warranty is... Read more
Updated Apple MacBook Price Trackers
Our Apple award-winning MacBook Price Trackers are continually updated with the latest information on prices, bundles, and availability for 16″ and 14″ MacBook Pros along with 13″ and 15″ MacBook... Read more
Every model of Apple’s 13-inch M3 MacBook Air...
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 are the lowest currently available for new 13″ M3 MacBook Airs among... Read more
Sunday Sale: Apple iPad Magic Keyboards for 1...
Walmart has Apple Magic Keyboards for 12.9″ iPad Pros, in Black, on sale for $150 off MSRP on their online store. Sale price for online orders only, in-store price may vary. Order online and choose... Read more
Apple Watch Ultra 2 now available at Apple fo...
Apple has, for the first time, begun offering Certified Refurbished Apple Watch Ultra 2 models in their online store for $679, or $120 off MSRP. Each Watch includes Apple’s standard one-year warranty... Read more

Jobs Board

DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
IT Systems Engineer ( *Apple* Platforms) - S...
IT Systems Engineer ( Apple Platforms) at SpaceX Hawthorne, CA SpaceX was founded under the belief that a future where humanity is out exploring the stars is Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.