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

Whitethorn Games combines two completely...
If you have ever gone fishing then you know that it is a lesson in patience, sitting around waiting for a bite that may never come. Well, that's because you have been doing it wrong, since as Whitehorn Games now demonstrates in new release Skate... | Read more »
Call of Duty Warzone is a Waiting Simula...
It's always fun when a splashy multiplayer game comes to mobile because they are few and far between, so I was excited to see the notification about Call of Duty: Warzone Mobile (finally) launching last week and wanted to try it out. As someone who... | Read more »
Albion Online introduces some massive ne...
Sandbox Interactive has announced an upcoming update to its flagship MMORPG Albion Online, containing massive updates to its existing guild Vs guild systems. Someone clearly rewatched the Helms Deep battle in Lord of the Rings and spent the next... | Read more »
Chucklefish announces launch date of the...
Chucklefish, the indie London-based team we probably all know from developing Terraria or their stint publishing Stardew Valley, has revealed the mobile release date for roguelike deck-builder Wildfrost. Developed by Gaziter and Deadpan Games, the... | Read more »
Netmarble opens pre-registration for act...
It has been close to three years since Netmarble announced they would be adapting the smash series Solo Leveling into a video game, and at last, they have announced the opening of pre-orders for Solo Leveling: Arise. [Read more] | Read more »
PUBG Mobile celebrates sixth anniversary...
For the past six years, PUBG Mobile has been one of the most popular shooters you can play in the palm of your hand, and Krafton is celebrating this milestone and many years of ups by teaming up with hit music man JVKE to create a special song for... | Read more »
ASTRA: Knights of Veda refuse to pump th...
In perhaps the most recent example of being incredibly eager, ASTRA: Knights of Veda has dropped its second collaboration with South Korean boyband Seventeen, named so as it consists of exactly thirteen members and a video collaboration with Lee... | Read more »
Collect all your cats and caterpillars a...
If you are growing tired of trying to build a town with your phone by using it as a tiny, ineffectual shover then fear no longer, as Independent Arts Software has announced the upcoming release of Construction Simulator 4, from the critically... | Read more »
Backbone complete its lineup of 2nd Gene...
With all the ports of big AAA games that have been coming to mobile, it is becoming more convenient than ever to own a good controller, and to help with this Backbone has announced the completion of their 2nd generation product lineup with their... | Read more »
Zenless Zone Zero opens entries for its...
miHoYo, aka HoYoverse, has become such a big name in mobile gaming that it's hard to believe that arguably their flagship title, Genshin Impact, is only three and a half years old. Now, they continue the road to the next title in their world, with... | Read more »

Price Scanner via MacPrices.net

B&H has Apple’s 13-inch M2 MacBook Airs o...
B&H Photo has 13″ MacBook Airs with M2 CPUs and 256GB of storage in stock and on sale for up to $150 off Apple’s new MSRP, starting at only $849. Free 1-2 day delivery is available to most US... Read more
M2 Mac minis on sale for $100-$200 off MSRP,...
B&H Photo has Apple’s M2-powered Mac minis back in stock and on sale today for $100-$200 off MSRP. Free 1-2 day shipping is available for most US addresses: – Mac mini M2/256GB SSD: $499, save $... Read more
Mac Studios with M2 Max and M2 Ultra CPUs on...
B&H Photo has standard-configuration Mac Studios with Apple’s M2 Max & Ultra CPUs in stock today and on Easter sale for $200 off MSRP. Their prices are the lowest available for these models... Read more
Deal Alert! B&H Photo has Apple’s 14-inch...
B&H Photo has new Gray and Black 14″ M3, M3 Pro, and M3 Max MacBook Pros on sale for $200-$300 off MSRP, starting at only $1399. B&H offers free 1-2 day delivery to most US addresses: – 14″ 8... Read more
Department Of Justice Sets Sights On Apple In...
NEWS – The ball has finally dropped on the big Apple. The ball (metaphorically speaking) — an antitrust lawsuit filed in the U.S. on March 21 by the Department of Justice (DOJ) — came down following... Read more
New 13-inch M3 MacBook Air on sale for $999,...
Amazon has Apple’s new 13″ M3 MacBook Air on sale for $100 off MSRP for the first time, now just $999 shipped. Shipping is free: – 13″ MacBook Air (8GB RAM/256GB SSD/Space Gray): $999 $100 off MSRP... Read more
Amazon has Apple’s 9th-generation WiFi iPads...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Discounted 14-inch M3 MacBook Pros with 16GB...
Apple retailer Expercom has 14″ MacBook Pros with M3 CPUs and 16GB of standard memory discounted by up to $120 off Apple’s MSRP: – 14″ M3 MacBook Pro (16GB RAM/256GB SSD): $1691.06 $108 off MSRP – 14... Read more
Clearance 15-inch M2 MacBook Airs on sale for...
B&H Photo has Apple’s 15″ MacBook Airs with M2 CPUs (8GB RAM/256GB SSD) in stock today and on clearance sale for $999 in all four colors. Free 1-2 delivery is available to most US addresses.... Read more
Clearance 13-inch M1 MacBook Airs drop to onl...
B&H has Apple’s base 13″ M1 MacBook Air (Space Gray, Silver, & Gold) in stock and on clearance sale today for $300 off MSRP, only $699. Free 1-2 day shipping is available to most addresses in... Read more

Jobs Board

Medical Assistant - Surgical Oncology- *Apple...
Medical Assistant - Surgical Oncology- Apple Hill Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply 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
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
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
Business Analyst | *Apple* Pay - Banco Popu...
Business Analyst | Apple PayApply now " Apply now + Apply Now + Start applying with LinkedIn Start + Please wait Date:Mar 19, 2024 Location: San Juan-Cupey, PR Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.