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

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... | Read more »
Price of Glory unleashes its 1.4 Alpha u...
As much as we all probably dislike Maths as a subject, we do have to hand it to geometry for giving us the good old Hexgrid, home of some of the best strategy games. One such example, Price of Glory, has dropped its 1.4 Alpha update, stocked full... | Read more »
The SLC 2025 kicks off this month to cro...
Ever since the Solo Leveling: Arise Championship 2025 was announced, I have been looking forward to it. The promotional clip they released a month or two back showed crowds going absolutely nuts for the previous competitions, so imagine the... | Read more »
Dive into some early Magicpunk fun as Cr...
Excellent news for fans of steampunk and magic; the Precursor Test for Magicpunk MMORPG Crystal of Atlan opens today. This rather fancy way of saying beta test will remain open until March 5th and is available for PC - boo - and Android devices -... | Read more »
Prepare to get your mind melted as Evang...
If you are a fan of sci-fi shooters and incredibly weird, mind-bending anime series, then you are in for a treat, as Goddess of Victory: Nikke is gearing up for its second collaboration with Evangelion. We were also treated to an upcoming... | Read more »
Square Enix gives with one hand and slap...
We have something of a mixed bag coming over from Square Enix HQ today. Two of their mobile games are revelling in life with new events keeping them alive, whilst another has been thrown onto the ever-growing discard pile Square is building. I... | Read more »
Let the world burn as you have some fest...
It is time to leave the world burning once again as you take a much-needed break from that whole “hero” lark and enjoy some celebrations in Genshin Impact. Version 5.4, Moonlight Amidst Dreams, will see you in Inazuma to attend the Mikawa Flower... | Read more »
Full Moon Over the Abyssal Sea lands on...
Aether Gazer has announced its latest major update, and it is one of the loveliest event names I have ever heard. Full Moon Over the Abyssal Sea is an amazing name, and it comes loaded with two side stories, a new S-grade Modifier, and some fancy... | Read more »
Open your own eatery for all the forest...
Very important question; when you read the title Zoo Restaurant, do you also immediately think of running a restaurant in which you cook Zoo animals as the course? I will just assume yes. Anyway, come June 23rd we will all be able to start up our... | Read more »
Crystal of Atlan opens registration for...
Nuverse was prominently featured in the last month for all the wrong reasons with the USA TikTok debacle, but now it is putting all that behind it and preparing for the Crystal of Atlan beta test. Taking place between February 18th and March 5th,... | Read more »

Price Scanner via MacPrices.net

AT&T is offering a 65% discount on the ne...
AT&T is offering the new iPhone 16e for up to 65% off their monthly finance fee with 36-months of service. No trade-in is required. Discount is applied via monthly bill credits over the 36 month... Read more
Use this code to get a free iPhone 13 at Visi...
For a limited time, use code SWEETDEAL to get a free 128GB iPhone 13 Visible, Verizon’s low-cost wireless cell service, Visible. Deal is valid when you purchase the Visible+ annual plan. Free... Read more
M4 Mac minis on sale for $50-$80 off MSRP at...
B&H Photo has M4 Mac minis in stock and on sale right now for $50 to $80 off Apple’s MSRP, each including free 1-2 day shipping to most US addresses: – M4 Mac mini (16GB/256GB): $549, $50 off... Read more
Buy an iPhone 16 at Boost Mobile and get one...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering one year of free Unlimited service with the purchase of any iPhone 16. Purchase the iPhone at standard MSRP, and then choose... Read more
Get an iPhone 15 for only $299 at Boost Mobil...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering the 128GB iPhone 15 for $299.99 including service with their Unlimited Premium plan (50GB of premium data, $60/month), or $20... Read more
Unreal Mobile is offering $100 off any new iP...
Unreal Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering a $100 discount on any new iPhone with service. This includes new iPhone 16 models as well as iPhone 15, 14, 13, and SE... Read more
Apple drops prices on clearance iPhone 14 mod...
With today’s introduction of the new iPhone 16e, Apple has discontinued the iPhone 14, 14 Pro, and SE. In response, Apple has dropped prices on unlocked, Certified Refurbished, iPhone 14 models to a... Read more
B&H has 16-inch M4 Max MacBook Pros on sa...
B&H Photo is offering a $360-$410 discount on new 16-inch MacBook Pros with M4 Max CPUs right now. B&H offers free 1-2 day shipping to most US addresses: – 16″ M4 Max MacBook Pro (36GB/1TB/... Read more
Amazon is offering a $100 discount on the M4...
Amazon has the M4 Pro Mac mini discounted $100 off MSRP right now. Shipping is free. Their price is the lowest currently available for this popular mini: – Mac mini M4 Pro (24GB/512GB): $1299, $100... Read more
B&H continues to offer $150-$220 discount...
B&H Photo has 14-inch M4 MacBook Pros on sale for $150-$220 off MSRP. B&H offers free 1-2 day shipping to most US addresses: – 14″ M4 MacBook Pro (16GB/512GB): $1449, $150 off MSRP – 14″ M4... Read more

Jobs Board

All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.