TweetFollow Us on Twitter

SimpleServer
Volume Number:10
Issue Number:8
Column Tag:New Apple Technology

SimpleServer

A Simple OLE 2.01 Object Server Revealed

By Michael Fanning, Microsoft

Note: Source code files accompanying article are located on MacTech CD-ROM or source code disks.

Code Reuse or Object Reuse?

Code reuse has often been cited as a significant goal of object-oriented programming. Successful examples of code reuse have been few, despite the now-widespread adoption of object-oriented languages and techniques. Applications frameworks, such as MacApp, TCL, and PowerPlant have been reused extensively-but they’re about the only case of code reuse to which one can point. These examples represent not only the success, but also the failure, of object-oriented programming to date: it focused on the reuse of CODE rather than the reuse of OBJECTS. Up to now, it has been impossible to reuse an object without access to its source code-or at least, a static library to which one’s own code (written in the same language) could bind at link-time.

Microsoft Object Linking and Embedding (OLE), version 2.01, addresses this fundamental problem of reusing code. Using OLE, any object can make its services available to any other object at run-time. Objects can be mixed, matched, and reused without regard to the language in which they were written or the vendor from which they came.

Using OLE, you can define any arbitrary service-an “interface” -which any object can then share with any other object. For example, you could easily define an interface for spell-checking which any other object could bind to at run-time, without knowing (or caring) who wrote the spell-checking service or in what language. Similarly, you could define an interface for charting data, for recalculating spreadsheet data, or for rendering photorealistic images.

OLE provides a set of standard services, which are available to any application that wants to use them. These standard services include interfaces for many features that are of interest to software developers today, such as compound documents (documents that include arbitrary data, like a video clip or a CAD blueprint in a word processor) and Visual Editing (the ability to edit that arbitrary data within the context of the containing application, without having to switch to another application). These OLE services provide a structure within which objects interact to reuse each other’s unique features, thus improving the end-user experience (which is what it’s all about, after all).

Goal of This Article

This article describes how basic OLE features were implemented in a simple Macintosh application. The application does not implement every OLE feature; indeed, one of OLE’s most important features-Visual Editing-has not been implemented in the sample to ensure that it is as easy as possible to examine and understand. (Visual Editing will be added to the sample in a subsequent article). Enough features have been added to give you the flavor of OLE development and to let you understand its basic concepts and idioms. The OLE 2.01 SDK CD that accompanies this issue of MacTech will provide you the means to get started in adding OLE support to your application today.

It is important to note that an OLE application is just that: an application much like those your firm develops and sells today. SimpleServer is a stand-alone, double-clickable application designed to provide simple drawing services to any other object. Just as we did with this sample application, you can easily add OLE support to your application, without changing its nature, its distribution, or its business model.

Now, let’s put on our code snorkels, and dive in!

SimpleServer, Revealed

SimpleServer is a minimal implementation of an OLE 2.0 embeddable object server written in C++. The implementation of OLE in this sample code allows SimpleServer objects to be embedded in OLE containers and saved in compound documents.

The first section of this article contains a general description of the sample code source files. The second tracks the communication between SimpleServer and an OLE container as a SimpleServer object is embedded. Finally, I’ve included a glossary of important OLE concepts: consult this section if you come across an unfamiliar term. If you’re new to OLE, or just that kind of person, you might want to go ahead and review this section before reading on. The rest of us who leave manuals wrapped in plastic until all hell breaks loose will continue on without you.

The SimpleServer Source Files

The SimpleServer source files (located in “Sample Code (OLE):SimpleServer:src”on the OLE SDK CD bound in this issue) can be broken out into three groups: a set of source files which provide the basic structure and functionality of the application; a set of sources which contain the OLE-specific code, file utilities, error reporting, and debug information; and sources taken from the sample OLE UI library.

Note: Every OLE interface is in its own file, for easy review, named CInterface (where Interface is the name of the OLE interface implemented in the file).

The Basic Application

IUnknown - IUnknown is the abstract base class for all SimpleServer objects. Defined in the OLE header compobj.h, its methods (like the member functions of all standard OLE interfaces) are pure virtual and are implemented in SimpleServer’s derived object classes.

Class Source Files

Capplication.cp - Methods used to initialize the Mac Toolbox, set up menus, install AppleEvent handlers, and handle events and menu commands. CApplication tracks the life of the application object through its reference-counting methods (AddRef and Release), registers SimpleServer in the Registration Database, and instantiates the application’s ClassFactory.

These tasks (and other OLE-specific tasks mentioned in the next sections) will be covered in more detail later in the article.

Cwindow.cp (derived from IUnknown) - A window class containing methods for handling mouse, keyboard, update, and activate events.

Cdocument.cp (derived from CWindow) - A document class which instantiates the primary interfaces associated with an embeddable object: IDataObject, IOleObject, and IPersistStorage The CDocument class acquires all the interface pointers it will use during a document’s lifetime when a document is initialized. These pointers are stored as member data and are released when the document is deallocated.

Ctoolbar.cp (derived from Cwindow) - A small toolbar class.

CShape.cp (derived from CObject) - A shape class. Shape objects are drawn upon a document and maintained in a linked list associated with a CDocument.

Utility Source Files

AEvents.cp - Handlers for the required AppleEvents and one special OLE 2.01 AppleEvent (‘EMBD’) which indicates the application has been launched as a result of an embedding.

OleErrors.cp - Error routines for evaluating results of Toolbox and OLE function calls. Also contains functions which return human-readable strings for SCODES.

Debug.h/Debug.c - A set of macros for asserting; includes macros for dumping messages to the OLE LRPCSpy utility on entering an interface method or calling AddRef or Release. (LRPCSpy is described in detail later in the article).

Utitilies.cp - Utilities for detecting System 7. Contains two OLE-specific utilities: one for freeing pointers to blocks of memory allocated by OLE and another for writing to the OLE registration database.

SimpleServer.r - Resource file for SimpleServer.

OLE-Specific Source Files

CClassFactory.cp - Implementation of the IClassFactory interface.

CDataObject.cp - Implementation of the IDataObject interface, which is used to transfer data to and from an OLE object. IDataObject methods set and retrieve data (GetData, SetData), enumerate supported data formats (EnumFormatEtc), and establish connections between an object and its container.

COleObject.cp - Implementation of IOleObject, the primary means by which an embedded object provides functionality to its container.

CPersistStorage.cp - Implementation of IPersistStorage. Objects generated by a server’s IClassFactory::CreateInstance method are initialized by calling either IPersistStorage::InitNew or IPersistStorage::Load.

OleMessageFilter.cp - Installs a minimal implementation of the IMessageFilter interface, which allows an application to handle incoming Macintosh events while waiting for synchronous OLE calls to complete. Adding IMessageFilter is straightforward: the OLE Sample User Interface Library contains a standard implementation (in msgfiltr.c) that an application can use without modification.

UI Source Files : The following files included in the SimpleServer project are taken from the OLE Sample UI source code: busy.c, common.c, geticon.c, msgfiltr.c, ole2ui.c, ole2ui.r, olestd.c, regdb.c, utility.c.

The OLE Sample User Interface Library contains source code for the standard OLE dialogs (for example, the Insert Object and Paste Special dialogs), as well as helper functions for memory management, object feedback (the way an object appears in various editing states), linking, data transfer, debugging and more. A full discussion of the UI Library is beyond the scope of this article. For more information, see the “OLE 2.01 UI Help” help file included with the OLE SDK.

Running SimpleServer

SimpleServer is a regular Macintosh application. It can be launched and used like any other Mac application. Go ahead and try it. It is already built and can be found in the Applications folder on the OLE SDK CD.

Stepping Through SimpleServer

SimpleServer comes with a ThinkC Project and an MPW makefile. (NOTE: In order to link SimpleServer in ThinkC, you’ll need to add OutputDebugString to Ole2Lib.near.debug.v before compiling and linking. To make the change, open the .v file in any text editor, add a newline, and type out the function name (with matching case). The function prototype is located in the SimpleServer source file, Debug.h. If you’d like to use OutputDebugString in your own application, you’ll need to include a function prototype as well.)

After compiling, launch SimpleServer and set a breakpoint on the first statement of main() in file main.cp. To see how an OLE server typically handles startup, step through its initialization routine. Eventually, SimpleServer will fall into its event loop where you can set a breakpoint on the call to gApp->DisposeApplication and step through its shutdown code.

Here’s a synopsis of what SimpleServer does on startup and exit (calls to the OLE API are marked in boldface):

1. main(), main.cp - Instantiates a CApplication object.

• The constructor for CApplication does nothing more than initialize member variables (this is consistent across all SimpleServer class constructors).

2. CApplication::InitApplication - Initializes the CApplication object

• Calls standard Macintosh initialization routines.

• Retrieves and displays application menus.

• Installs handlers for the required AppleEvents and the OLE ‘EMBD’ event.

• Instantiates a toolbar.

• Calls OleInitApplication.

3. CApplication::OleInitApplication - Initializes OLE

• Calls InitOleManager. This routine loads OLE into memory if it is not already present, registers application context information and sets up a table which exposes the OLE API to the application. Passing the OLEMGR_BIND_NORMAL flag specifies a normal launch, bind, and AddRef of the OLE libraries. A call to InitOleManager is always balanced by a call to UninitOleManager in an application’s shutdown code.

• Calls OleInitialize. This API fully initializes OLE. At this point, OLE functions can be called by an application. An argument of NULL for pMalloc indicates that OLE should use its default implementation of IMalloc to handle process memory. An application always calls OleUninitialize in its shutdown code to balance a call to OleInitialize.

• Calls OleUpdateRegDB.

4. CApplication::OleUpdateRegDB - Updates the Registration Database

• Opens the OLE 1.0 registration database (“Embedding Preferences”) and registers SimpleServer if references to it do not already exist in the file.

• Opens the OLE 2.01 registration database (“Registration Database”) and registers SimpleServer, if necessary. A helper function, WriteToOleReg, is used to handle this procedure and can be found in Utilities.cp.

SimpleServer registers itself in the OLE 1.0 Embedding Preferences because OLE provides a compatibility layer that allows OLE 1 and 2 applications to interact with each other transparently. SimpleServer objects can be embedded in all OLE 1.0 client applications.

5. CApplication::RegisterClassFactory - Instantiates and registers the ClassFactory

• Instantiates an instance of CClassFactory and assigns its pointer to a CApplication member variable.

• Calls CoRegisterClassObject with SimpleServer’s CLSID and a pointer to the just-instantiated class factory. Another CApplication member variable (m_CoRegisterResult) will be filled out with a value identifying the object class. This value is passed to CoRevokeClassObject in order to revoke the class registration on application shutdown. After calling CoRegisterClassObject, other OLE applications can now connect to SimpleServer’s object class.

6. CApplication::OleMessageFilterRegister - Registers the MessageFilter

• Instantiates and registers a standard implementation of the IMessageFilter interface. The OLE libraries continually call an application’s IMessageFilter::MessagePending method while waiting for a reply from a synchronous OLE call. This allows an application the opportunity to process critical events such as update, activate, and os events. Applications call WaitNextEvent within this method (with a sleep parameter greater than zero) and act on the ‘urgent’ events listed above.

7. CApplication::OleLockApplication - Locks the CApplication object in memory

• Calls CoLockObjectExternal. This routine sets a strong reference on the CApplication object which explicitly locks the application in memory on behalf of the user (a strong reference dictates that an object will remain in memory even if its reference count falls to zero). Once a context for the launch has been established (that is, whether it was launched from the Finder or as the result of an embedding), the CApplication will be unlocked and the life of the application will be subject to the standard rules of reference counting. Note the ‘artificial’ AddRef immediately preceding the call and the Release following it. This strategy applies an artificial weak reference to the CApplication object for purposes similar to CoLockObjectExternal and should only be used within the scope of a single function.

8. HandleOpenApplication, AEvents.cp - SimpleServer processes an ‘oapp’ AE

• In its ‘oapp’ handler, SimpleServer creates a document (CApplication::CreateNewDocument).

9. CApplication::CreateNewDocument - Creates and initializes a new document

• Instantiates a new CDocument object.

• Calls CWindow::InitWindow in order to create a window (CDocument is derived from CWindow). The CDocument this pointer is retained by a call to SetWRefCon .

• Instantiates CDataObject, COleObject, and CPersistStorage; their pointers are retained as member data.

• Increments the application document count.

10. CApplication::DisposeApplication, CApplication::OleCleanup - Cleanup on shutdown

• Calls CApplication::OleCleanup to revoke the class object from the class factory table. Revokes the application IMessageFilter. Calls OleUninitialize and UninitOleManager.

After launching and exiting the sample, SimpleServer is registered in the Registration Database. Once registered, containers that support insertable objects can now be used to embed a SimpleServer shape object, which is what we’ll look at next.

Embedding a SimpleServer Object

LRPCSpy

The OLE SDK includes a utility, called LRPCSpy, which we’ll use to track the communication between SimpleServer and its container as a SimpleServer object is embedded. LRPC stands for lightweight remote procedure call, the mechanism by which OLE transfers data between processes (referred to as “lightweight” because the communication is currently restricted to processes on one machine). OLE has been carefully designed so that the LRPC mechanism can be easily replaced with a fully-distributable RPC based on OSF DCE RPC (Open Software Foundation Distributed Computing Environment Remote Procedure Call). This will be done in a future version of OLE.

LRPCSpy is an extremely useful tool that displays messages from the debug version of the OLE Manager. These messages track inter-process communication between a container and server. LRPCSpy displays method names as they are called, the arguments passed by the caller, and the return value from the callee. When debugging an OLE application, LRPCSpy will show how much progress was made before failure. Comparing the output to that generated by a working container/server combination can be invaluable during development.

OLE2 applications can write their own messages to LRPCSpy by calling OutputDebugString, an undocumented OLE routine. OutputDebugString can be called after adding a function prototype your project (and manually typing the function name into your OLE library .v file, if compiling under ThinkC). SimpleServer writes a debug message to LRPCSpy on entry of any interface method and dumps a reference count identifying any object which is AddRef’ed or Release’d.

For the next debugging session, be sure LPRCSpy is running in the background and the Extensions folder contains DDEWatchInit and the debug version of the OleManager. Set a breakpoint on CClassFactory::CreateInstance (CClassFactory.cp) and launch the OLE 2.01 Test Container application (Cl2Test). From the Edit menu, choose “Insert Object”. From the Object Type list, select “Simple OLE 2.01 Server Document” and click OK.

SimpleServer should now launch and stop at the breakpoint at CClassFactory::CreateInstance. When stepping through the debugger, we see a call to CDocument::CreateDocument. (Watch LRPCSpy as you step past this call. On creation of a document, SimpleServer AddRef’s the object three times, once for each instantiated interface (IDataObject, IOleObject, and IPersistStorage). The IUnknown implementation for these interface classes delegates all calls to CDocument. CDataObject::QueryInterface, for example, passes the call to CDocument::QueryInterface which actually handles the request. Calls to AddRef and Release are similarly delegated to the document class; reference counts are still maintained at the interface level, to assist in debugging.

Back in LRPCSpy, the “LRPC” window shows that SimpleServer’s CreateInstance method has been called but has not yet returned. Press the command-key for ‘Go’ from within whatever debugger you are using and watch the conversation between the container and server. In the following section, SimpleServer and Cl2Test are referred to by their Creator codes, just as they are in LRPCSpy output. SimpleServer’s creator code is ‘SiSe’; Cl2Test’s creator code is ‘CLT2’. The “>” character indicates the direction of the conversation (for example, “CLT2 > SiSe IClassFactory::CreateInstance” means Cl2Test called SiSe’s IClassFactory::CreateInstance method).

1. CLT2 > SiSe IClassFactory::CreateInstance.

2. CLT2 > SiSe QueryInterface for IPersistStorage. SimpleServer recognizes the IID for IPersistStorage and returns the appropriate interface pointer.

3. CLT2 > SiSe IPersistStorage::InitNew. Initializes the object retrieved by CreateInstance, above.

4. CLT2 > SiSe QueryInterface for IDataObject and IOleObject. SiSe returns the requested pointers.

What the heck just happened? Cl2Test called OleCreate and passed SimpleServer’s CLSID as the requested object type and the IID for the IOleObject interface. OLE launches SimpleServer after retrieving its location from the registration database) and calls its class factory (#1, above) to create a new SimpleServer object. OLE retrieves a pointer to IPersistStorage (#2) and calls InitNew (#3) to give SimpleServer a chance to initialize the object. Finally, OLE queries the object for IOleObject (#4) and returns the interface pointer to Cl2Test. IDataObject is retrieved by OLEfor internal use.

5. CLT2 >SiSe IOleObject::SetClientSite. Cl2Test passes a pointer to its IOleClientSite for SimpleServer to retain. All containers implement IOleClientSite, the primary means of communication between an object and its container.

6. CLT2 > SiSe IOleObject::Advise. Establishes a connection between SimpleServer and Cl2Test which will be used to notify the container when an object is saved, closed, or renamed.

7. CLT2 > SiSe IOleObject::SetMoniker. A moniker is to an object what an alias is to a file: it’s a conceptual handle to a link source (that is, an object) which can be stored with and dereferenced by a linking application.SimpleServer does not support linking and so returns E_NOTIMPL (not implemented) from the method.

8. CLT2 > SiSe IDataObject::QueryGetData. Cl2Test asks whether a PICT presentation is available. SimpleServer responds in the affirmative.

9. CLT2 > SiSe IDataObject::DAdvise. This creates another advisory connection which will be used to notify the container when any data in the object has changed. SimpleServer sends an OnDataChange notification before returning from the call. (Note: the LRPCSpy output window lists this method name as ‘Advise’. The function was renamed during OLE development to differentiate the call from the IOleObject::Advise method.)

10. LockConnection. LockConnection is an internal OLE routine used to manage the LRPC connection between applications. Since this involves no SimpleServer code, we’ll skip an explanation.

11. CLT2 > SiSe IOleObject::GetMiscStatus. SimpleServer returns OLE_S_USEREG indicating that the value should be retrieved from the Registration Database.

12. CLT2 > SiSe IOleObject::GetExtent. Cl2Test requests the extent (the width and height) of the object.

13. CLT2 > SiSe IOleObject::SetHostNames. Cl2Test passes user-presentable text strings for the name of the container application and the container object. SimpleServer concatenates the strings and sets the window title of the embedded object document to this value.

14. CLT2 > SiSe IOleObject::DoVerb. Cl2Test asks SimpleServer to invoke its primary verb. . An OLE verb is an operation supported by a server. OLEIVERB_PRIMARY is that verb which is invoked on double-clicking an object in its container. For SimpleServer, OLEIVERB_PRIMARY activates the server, loads the object, and puts the user in editing mode.

15. SiSe > CLT2 IOleClientSite::ShowObject. SimpleServer calls this to request that the container scroll the object into view. This ensures that the object’s presentation is visible.

16. SiSe > CLT2 IOleClientSite::OnShowWindow. OnShowWindow(true) lets Cl2Test know that the server object window is visible. The container “hatches” the object presentation as a visual indicator that the object is being edited in another window.

At this point, try drawing a few shapes into the SimpleServer document window and note the LRPCSpy output.

17. SiSe > CLT2 IAdviseSink::OnDataChange. SimpleServer sends an OnDataChange notification to Cl2Test as each shape is drawn. Cl2Test updates its presentation.

Delete a shape (from the Edit menu, choose “Delete Last Shape”, or press command-D).

18. SiSe > CLT2 IAdviseSink::OnDataChange. SimpleServer calls OnDataChange again to reflect the change in the server object.

Now close the SimpleServer window. Back in LRPCSpy, examine the resulting messages:

19. SiSe > CLT2 IOleClientSite::SaveObject. SimpleServer asks Cl2Test to save the object. Cl2Test calls OleSave, an OLE helper function which retrieves SimpleServer’s CLSID (GetClassID), writes it to the storage, and then invokes SimpleServer’s IPersistStorage::Save method. In IPersistSave, SimpleServer writes out the object data. Afterwards, Cl2Test can write additional data to the same storage. Cl2Test calls IPersistStorage::SaveCompleted to let SimpleServer know the storage can be written to again. Finally, SimpleServer sends an OnSave notification to Cl2Test’s IAdviseSink.

20. SimpleServer sends two final notification messages to the container. OnShowWindow(false) lets Cl2Test know that SimpleServer is hiding its object window. Cl2Test redraws the object without hatching. OnClose indicates the object is closing.

Back in Cl2Test, the SimpleServer object displays in the document window. Double-click the object in order to open it again. The LRPCSpy output is similar to that generated when creating an object, but is briefer because the work of creating the object has already been accomplished. Note the lack of any calls to QueryInterface on the part of Cl2Test. Cl2Test retains the pointers to the object’s OLE interfaces it previously acquired:

21. CLT2 > SiSe IClassFactory::CreateInstance.

22. The OLE calls its internal IStubManager::LockConnection method.

23. Cl2Test > SiSe IPersistStorage::Load. CLT2 passes the persistent representation of the object created on the previous call to IPersistStorage::Save. SimpleServer reads this information and uses it to fill out an instance of CDocument.

24. CLT2 > SiSe IDataObject::Advise.

25. CLT2 > SiSe IOleObject::SetClientSite.

26. CLT2 > SiSe IOleObject::SetHostNames

27. CLT2 > SiSe IOleObject::Advise

28. CLT2 > SiSe IOleObject::SetMoniker

29. CLT2 > SiSe IOleObject::DoVerb

30. SiSe > CLT2 IOleClientSite::ShowObject

31. SiSe > CLT2 IOleClientSite::OnShowWindow

Whew!

The LRPCSpy output looks like an awful lot of work, but in fact, all of this interaction happens without a user’s knowledge and, in many cases, without a developer’s concern. In fact, it’s the code that lies within and between interface calls that gives OLE its real power and flexibility.

Tracking LRPC conversation, however, is a good way to become familiar with OLE and how it goes about its business. A strategy such as SimpleServer uses to generate messages during execution can also go a long way to assist debugging.

Now What?

In this simple sample application, you have seen how support for OLE can be implemented in an application using the headers, libraries, and run-time on the OLE SDK CD that accompanies this article. Again, we do not claim that this sample application is complete-it would have to support Visual Editing to even approach completeness-but we will defer the addition of Visual Editing until a later issue of MacTech (this issue’s full enough already!).

And when your implementation of support for OLE is completed, your application will be able to interact with those from the other Macintosh software vendors now completing their OLE support, including Adobe, Aldus, Brio, Caere, Calera, EBT, Microsoft, Oracle, PowerSoft, Shapeware, Summit, and others.

OLE 2.01 for the Macintosh is in final form-it is not a beta; you can ship its redistributable elements today, without paying any fees to Microsoft, Apple, or anyone else. These are also the terms under which OLE 2.01 for the Power Macintosh will ship, later this summer. For your convenience, a beta version of OLE 2.01 for the Power Macintosh is included on the OLE CD.

Future versions of OLE will support additional features, including an inter-object event model (OLE Controls), distributed services, irregularly-shaped objects, database access, etc. Combined, these features will make OLE even more approachable and powerful for developers and end users. This incremental evolution of OLE ensures that it continues to progress in the direction most demanded by software developers-and, more importantly, by end-users. For more information on the future of OLE, see the white papers and backgrounders in the “White Papers” folder on the OLE CD.

But when thinking about the future, don’t forget the present. Right now, OLE 2.01 provides the technology and features that you need to turn your existing applications into powerful, reuseable objects. OLE has made the dream of component software a reality, today. Don’t wait to get started!

Some Important OLE Terms and Concepts

GUIDs, IIDs, and CLSIDs - GUIDs are globally unique identifiers (sometimes referred to as universally unique identifiers). They are 128-bit values used to identify OLE interfaces and object classes (something like an application Creator code identifies an application, only in 16 bytes, not 4). SimpleServer uses two types of GUIDs: IIDs and CLSIDs.

IIDs, or interface identifiers, do just that: identify interfaces. OLE 2 defines IIDs for every standard interface. IIDs are used typically when requesting an instance of an interface implementation. CLSIDs, or class identifiers, identify object classes. CLSIDs associate objects with particular OLE object servers.

Functions which require IIDs or CLSIDs as arguments are passed a reference to a GUID structure using the REFIID and REFCLSID types. In C, functions pass pointers to the structure (that is, &IID_xxx or &CLSID_xxx). C++ allows the & to be dropped.

To compare a GUID, IID, or CLSID for equality, compobj.h (in the Macintosh OLE SDK) defines the IsEqualGUID, IsEqualIID, and IsEqualCLSID functions (the latter two are actually macros which map to the IsEqualGUID function). For C++ applications, compobj.h overloads the ‘==’ operator for the GUID type (which also applies to IID and CLSID, of course), precluding the need to use the IsEqualxxx functions for comparison.

Interfaces - An OLE interface is an array of function pointers known as a virtual table (vtbl). The functions pointed to by the members of a vtbl are called the methods, or member functions, of the interface. In C++ terms, an interface is an abstract base class, composed of pure virtual functions, which specifies a protocol without providing an implementation. Although it is very convenient to use C++ to define interfaces - because C++ builds the vtbl for you - it is not necessary. Interfaces can be defined, implemented and used in any language (in fact, the Outline sample code which ships with the Mac OLE SDK is written entirely in C).

An OLE interface defines a contract between any object which implements the interface and any client which makes use of it. This contract includes the name of the interface and its methods (or member functions), the parameter types and names of the methods, and the purpose of each functions. An object must implement all methods in an interface and adhere to the defined protocol (or intent) of each routine.

The IUnknown Interface - IUnknown is the base interface from which all other OLE 2 interfaces are derived and it defines methods for three member functions (QueryInterface, AddRef, and Release). The IUnknown interface encapsulates two fundamental concepts behind interface and object operations: reference counting and pointer retrieval (or interface negotiation).

Interface Negotiation (IUnknown::QueryInterface) - Objects retrieve interface pointers through a mechanism known as interface negotiation. Each interface has a globally unique interface identifier (IID) by which it is known at run-time. The IID allows a client to dynamically determine, through a call to IUnknown::QueryInterface, the capabilities (i.e., supported interfaces) of other objects. The ability to discover an object’s capabilities at run-time avoids the need to have specific knowledge of objects at compile-time, a central idea behind the concept of reusable objects.

Given a pointer to an interface, pInterface, a caller can invoke pInterface->QueryInterface to retrieve pointers to other interfaces which are implemented by the object. The caller passes an IID to QueryInterface, which then returns either a NULL pointer, indicating that the interface is not supported, or a valid pointer to the requested interface.

Reference Counting (IUnknown::AddRef and IUnknown::Release) - The IUnknown::AddRef and ::Release methods comprise OLE reference counting, a mechanism for tracking the life of OLE 2 objects. An object keeps a usage count for each interface derived from IUnknown. An interface is never deallocated if its usage count is greater than zero. Objects (which might contain multiple interfaces) are kept alive if there are one or more references to one or more of their interfaces.

Reference counting ensures that an object is never disposed before all references to it are released. This strategy allows independent objects to obtain and release pointers to the same object with no coordination required.

HRESULTs and SCODEs - OLE methods and API calls use a new HRESULT return type in order to pass back a useful return value and/or an indication of status or error information. HRESULT values are defined to be zero for success, and non-zero if an error or informational status is being returned. If the result value is non-zero, the application calls GetScode to map the HRESULT into a known status code (or SCODE). ResultFromScode can be used to wrap a specific SCODE in an HRESULT for return from an interface method.

The Registration Database - OLE 2.01 optimizes performance by caching certain kinds of data in the Registration Database (reg db). OLE applications (and OLE itself) can retrieve the location or capabilities of an object class without the overhead of loading the object server.

Much of an OLE application’s registration information is stored under its class identifier (CLSID). Examples include the location of the object server (as a full path, or even as an alias), a list of the data formats the object supports, and whether it is embeddable in an OLE container.

The IClassFactory Interface - IClassFactory is used to create instances of an OLE object in memory. It contains only two methods beyond those derived from IUnknown: CreateInstance and LockServer. CreateInstance does the actual work of creating an uninitialized instance of an OLE object. LockServer can be used to lock a server in memory when it is advantageous to guarantee the server’s presence (for example, when a container plans to instantiate several instances of an object class).

The IMalloc Interface - IMalloc defines a set of methods for allocating and freeing memory. An application passes an instance of IMalloc as a parameter to the OLE library initialization function OleInitialize. Applications can implement IMalloc to integrate their own memory management schemes with the OLE libraries.

 
AAPL
$100.91
Apple Inc.
+0.38
MSFT
$44.97
Microsoft Corpora
-0.36
GOOG
$584.63
Google Inc.
-2.23

MacTech Search:
Community Search:

Software Updates via MacUpdate

Tidy Up 3.0.15.0 - Find duplicate files...
Tidy Up is a complete duplicate finder and disk-tidiness utility. With Tidy Up you can search for duplicate files and packages by the owner application, content, type, creator, extension, time... Read more
Parallels Desktop 10.0 - Run Windows app...
Parallels Desktop is simply the world's bestselling, top-rated, and most trusted solution for running Windows applications on your Mac. With Parallels Desktop for Mac, you can seamlessly run both... Read more
Apple Final Cut Pro X 10.1.3 - Professio...
Apple Final Cut Pro X is a professional video editing solution.Completely redesigned from the ground up, Final Cut Pro adds extraordinary speed, quality, and flexibility to every part of the post-... Read more
Apple Compressor 4.1.3 - Adds power and...
Compressor adds power and flexibility to Final Cut Pro X export. Customize output settings, work faster with distributed encoding, and tap into a comprehensive set of delivery features. Powerful... Read more
Chromium 36.0.1985.143 - Fast and stable...
Chromium is an open-source browser project that aims to build a safer, faster, and more stable way for all Internet users to experience the web. FreeSMUG-Free OpenSource Mac User Group build is... Read more
Macgo Blu-ray Player 2.10.6.1691 - Blu-r...
Macgo Mac Blu-ray Player can bring you the most unforgettable Blu-ray experience on your Mac. Overview Macgo Mac Blu-ray Player can satisfy just about every need you could possibly have in a Blu-ray... Read more
Apple Motion 5.1.2 - Create and customiz...
Apple Motion is designed for video editors, Motion 5 lets you customize Final Cut Pro titles, transitions, and effects. Or create your own dazzling animations in 2D or 3D space, with real-time... Read more
A Better Finder Rename 9.39 - File, phot...
A Better Finder Rename is the most complete renaming solution available on the market today. That's why, since 1996, tens of thousands of hobbyists, professionals and businesses depend on A Better... Read more
PopChar X 6.6 - Floating window shows av...
PopChar X helps you get the most out of your font collection. With its crystal-clear interface, PopChar X provides a frustration-free way to access any font's special characters. Expanded... Read more
MacUpdate Desktop 6.0.2 - Install Mac ap...
MacUpdate Desktop 6 brings seamless 1-click installs and version updates to your Mac. With a free MacUpdate account and MacUpdate Desktop 6, Mac users can now install almost any Mac app on macupdate.... Read more

Latest Forum Discussions

See All

Space Colors – Tips, Tricks, Strategies,...
Hello Cadets: Want to know what we thought about this hectic space combat/roguelike? Check out our Space Colors review! Space Colors is a cool shooter/roguelike from Team Chaos. You travel from planet to planet across a huge galaxy and complete a... | Read more »
Tap Sports Baseball – Tips, Tricks, and...
Tap Sports Baseball is a pretty simple game to learn, but that doesn’t mean it’s an easy game to master, by any means. To start your batting career off well, we thought we’d give you the heads up on some handy tips and tricks. Hey Batter-Batter:... | Read more »
Tap Sports Baseball Review
Tap Sports Baseball Review By Jennifer Allen on August 20th, 2014 Our Rating: :: LET'S PLAY BALLUniversal App - Designed for iPhone and iPad Tap Sports Baseball is briefly fun but lacks some important features.   | Read more »
Frontier Heroes Review
Frontier Heroes Review By Andrew Fisher on August 20th, 2014 Our Rating: :: BLAZES NO TRAILSUniversal App - Designed for iPhone and iPad Despite awesome visuals and great music, Frontier Heroes just doesn’t quite deliver enough fun... | Read more »
Echo Prime is Now on Sale for $0.99
Echo Prime is Now on Sale for $0.99 Posted by Jessica Fisher on August 20th, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
Star Realms Review
Star Realms Review By Andrew Fisher on August 20th, 2014 Our Rating: :: A STAR IS BORNUniversal App - Designed for iPhone and iPad Star Realms is an excellent adaptation of an outstanding deck-builder. With great visuals and an... | Read more »
This. Is. SPRINGFIELD! War comes to The...
This. Is. SPRINGFIELD! | Read more »
One Tap RPG Review
One Tap RPG Review By Campbell Bird on August 20th, 2014 Our Rating: :: DUNGEON SLIDERUniversal App - Designed for iPhone and iPad This casual arcade game introduces some very light rpg elements into its fantasy-themed pachinko... | Read more »
Goodbye Paywall – Table Tennis Touch Eli...
Goodbye Paywall – Table Tennis Touch Eliminates In-App Purchases Posted by Jessica Fisher on August 20th, 2014 [ permalink ] | Read more »
Go to Bed – An Interview With Touchfight...
Touchfight Games is an exciting new indie studio that was co-formed between game journalist and author Nathan Meunier, artist Leonard Kenyon, and programmer Jon Kenyon. Their debut game Go To Bed will be released this fall, and with all the... | Read more »

Price Scanner via MacPrices.net

Apple now offering certified refurbished 2014...
 The Apple Store is now offering Apple Certified Refurbished 2014 MacBook Airs for up to $180 off the cost of new models. An Apple one-year warranty is included with each MacBook, and shipping is... Read more
Best Buy’s College Student Deals: $100 off Ma...
Take an additional $100 off all MacBooks and iMacs, $50 off iPad Airs and iPad minis, at Best Buy Online with their College Students Deals Savings, valid through September 6th. Anyone with a valid .... Read more
MacBook Airs on sale for $100 off MSRP, free...
B&H Photo has three 2014 MacBook Airs on sale for $100 off MSRP. Shipping is free, and B&H charges NY sales tax only. They also include free copies of Parallels Desktop and LoJack for Laptops... Read more
Razer Taipan Mouse For Gamers And Non-Gamers...
If you’re a serious gamer on either Mac or Windows PCs, a serious gaming mouse is a necessity for first-tier performance. However, even if like me you’re not much of a gamer, there’s still a strong... Read more
15-inch 2.2GHz MacBook Pro on sale for $1899,...
Adorama has the new 15″ 2.2GHz Retina MacBook Pro on sale for $1899 including free shipping plus NY & NJ sales tax only. Their price is $100 off MSRP, and it’s the lowest price available for this... Read more
Mid-Size Tablet Shootout Posted: iPad mini wi...
I ‘m curious about how many iPads Apple is actually selling these days. It’s been widely rumored and anticipated that new models with A8 SoCs, 2 GB of RAM, 8 megapixel cameras, and fingerprint... Read more
The 15 Biggest iPad Air Problems And How To A...
What’s this? Fifteen “biggest” problems with the iPad Air? Does that mean there are a lot of smaller problems as well? Say it isn’t so! My old iPad 2 has manifested no hardware problems in three... Read more
TYLT Syncable-Duo, 2-in-1 USB Cable With Appl...
TYLT has introduced the Syncable-Duo, a universal cable solution for charging and syncing data to smartphones and tablets. The Syncable-Duo eliminates the need for multiple cables by incorporating... Read more
Save up to $140 off MSRP with Apple refurbish...
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
2.5GHz Mac mini on sale for $549, save $50
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

Jobs Board

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
*Apple* Solutions Consultant - Apple (United...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
Position Opening at *Apple* - Apple (United...
**Job Summary** Being a Business Manager at an Apple Store means you're the catalyst for businesses to discover and leverage the power, ease, and flexibility of Apple Read more
Position Opening at *Apple* - Apple (United...
**Job Summary** At the Apple Store, you connect business professionals and entrepreneurs with the tools they need in order to put Apple solutions to work in their Read more
Project Manager / Business Analyst, WW *Appl...
…a senior project manager / business analyst to work within our Worldwide Apple Fulfillment Operations and the Business Process Re-engineering team. This role will work Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.