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
$518.60
Apple Inc.
+0.64
MSFT
$40.18
Microsoft Corpora
+0.43
GOOG
$544.99
Google Inc.
+8.55

MacTech Search:
Community Search:

Software Updates via MacUpdate

Monolingual 1.5.9 - Remove unwanted OS X...
Monolingual is a program for removing unnecesary language resources from OS X, in order to reclaim several hundred megabytes of disk space. It requires a 64-bit capable Intel-based Mac and at least... Read more
Maya 2015 - Professional 3D modeling and...
Maya is an award-winning software and powerful, integrated 3D modeling, animation, visual effects, and rendering solution. Because Maya is based on an open architecture, all your work can be scripted... Read more
Starcraft II: Wings of Liberty 1.1.1.180...
Download the patch by launching the Starcraft II game and downloading it through the Battle.net connection within the app. Starcraft II: Wings of Liberty is a strategy game played in real-time. You... Read more
Sibelius 7.5.0 - Music notation solution...
Sibelius is the world's best-selling music notation software for Mac. It is as intuitive to use as a pen, yet so powerful that it does most things in less than the blink of an eye. The demo includes... Read more
Typinator 5.9 - Speedy and reliable text...
Typinator turbo-charges your typing productivity. Type a little. Typinator does the rest. We've all faced projects that require repetitive typing tasks. With Typinator, you can store commonly used... Read more
MYStuff Pro 2.0.16 - Create inventories...
MYStuff Pro is the most flexible way to create detail-rich inventories for your home or small business. Add items to MYStuff by dragging and dropping existing information, uploading new images, or... Read more
TurboTax 2013.r17.002 - Manage your 2013...
TurboTax guides you through your tax return step by step, does all the calculations, and checks your return for errors and overlooked deductions. It lets you file your return electronically to get... Read more
TrailRunner 3.8.769 - Route planning for...
Note: While the software is classified as freeware, it is actually donationware. Please consider making a donation to help support development. TrailRunner is the perfect companion for runners,... Read more
Flavours 1.1.10 - Create and apply theme...
Flavours is a Mac application that allow users to create, apply and share beautifully designed themes. Classy Give your Mac a gorgeous new look by applying delicious themes! Easy Unleash your... Read more
Spotify 0.9.8.296. - Stream music, creat...
Spotify is a streaming music service that gives you on-demand access to millions of songs. Whether you like driving rock, silky R&B, or grandiose classical music, Spotify's massive catalogue... Read more

Latest Forum Discussions

See All

Knights of Pen & Paper is Free for a...
Knights of Pen & Paper is Free for a Limited Time – Don’t Wait for a Natural 20, Get it Now! Posted by Rob Rich on April 16th, 2014 [ permalink ] | Read more »
R.B.I. Baseball 14 Review
R.B.I. Baseball 14 Review By Blake Grundman on April 16th, 2014 Our Rating: :: RETRO REVIVEDUniversal App - Designed for iPhone and iPad What was old is new again, as the MLB attempts to taking baseball gaming back to its retro... | Read more »
Noodlecake Studios Places Mikey Hooks on...
Noodlecake Studios Places Mikey Hooks on Sale, Releases Sneak Peek Trailer for Upcoming Sequel Mikey Boots Posted by Tre Lawrence on April 16th, 2014 [ | Read more »
Cosmic Mechanic Review
Cosmic Mechanic Review By Blake Grundman on April 16th, 2014 Our Rating: :: SLIGHTLY CREDIBLE MACHINEUniversal App - Designed for iPhone and iPad Creatives folks love the opportunity to have their wits tested, but there isn’t... | Read more »
ClutchPlay Games Releases Trailer for it...
ClutchPlay Games Releases Trailer for its Upcoming New Game, Skullduggery! | Read more »
Captain America: The Winter Soldier – Th...
Captain America: The Winter Soldier – The Official Game Review By Rob Thomas on April 16th, 2014 Our Rating: :: OUT IN THE COLDUniversal App - Designed for iPhone and iPad | Read more »
Strike Wing: Raptor Rising to Get a Huge...
Strike Wing: Raptor Rising to Get a Huge Update That Adds New Mode, Improved Graphics and More. Posted by Tre Lawrence on April 16th, 2014 [ | Read more »
Don’t be a Pygon, Download Horn Right No...
Don’t be a Pygon, Download Horn Right Now While it’s Still Free Posted by Rob Rich on April 16th, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
RollerCoaster Tycoon 4 Mobile Review
RollerCoaster Tycoon 4 Mobile Review By Jennifer Allen on April 16th, 2014 Our Rating: :: DISAPPOINTINGLY WEAKUniversal App - Designed for iPhone and iPad The RollerCoaster Tycoon franchise finally comes to iOS, but it’s a rather... | Read more »
148Apps Live on Twitch: Pivvot’s Looper...
On our latest Twitch stream, we’ll be playing a pair of minimalist arcade games, one that just got a big content update in Pivvot, and another that was inspired by it in 15 Coins. Whitaker Trebella, creator of Pivvot, will discuss the new modes... | Read more »

Price Scanner via MacPrices.net

Apple refurbished iPad Airs available startin...
Apple is now 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. The following Airs are available today: -... Read more
21-inch 2.7GHz iMac on sale for $1179, save $...
B&H Photo has the 21″ 2.7GHz iMac on sale for $1179 including free shipping plus NY sales tax only. Their price is $120 off MSRP. Add an iMac to your shopping cart, and B&H will offer an... Read more
Download our app, iTracx, for iOS and Android
MacPrices is proud to offer readers a free iOS app (iPhones, iPads, & iPod touch) and Android app (Google Play and Amazon App Store) called iTracx, which allows you to glance at today’s lowest... Read more
Education discounts shave up to $300 off the...
Purchase a new Mac at The Apple Store for Education and take up to $300 off MSRP. All teachers, students, and staff of any educational institution qualify for the discount. Shipping is free, and all... Read more
Save $50 on Mac mini Server
B&H Photo has the 2012 Mac mini Server on sale for $949 including free shipping plus NY sales tax only. Their price is $50 off MSRP. Read more
PhatWare’s “Ultimate Writing App For iOS” Ren...
PhatWare Corp. has announced it has renamed its new WritePro word processing app for iPhone and iPad: WritePad Pro. The decision to change the app’s name to leverages the strong brand awareness and... Read more
Full Resolution Photo Editor Tint Mint 1.0 Re...
California based independent developer, Jeffrey Sun, creator of the iOS app Modern Editor, has released Tint Mint, a new photography app for editing enthusiasts. The app costs a dollar, and it packs... Read more
16GB iPad mini (Apple refurbished) available...
The Apple Store has refurbished 1st generation 16GB iPad minis available for $249 including free shipping. Both black and white models are available. Read more
Save $120 on the 27-inch 3.2GHz Haswell iMac
B&H Photo has the 27″ 3.2GHz iMac on sale for $1679.99 including free shipping plus NY sales tax only. Their price is about $120 off MSRP. Read more
Using a Mac Doesn’t Eliminate The Heartbleed...
Low End Mac’s Dan Knight notes that any time you visit a website with an https: prefix or see that secure lock icon on your browser, some type of security software is busy trying to protect your data... Read more

Jobs Board

*Apple* Retail - Manager - Apple (United Sta...
Job SummaryKeeping an Apple Store thriving requires a diverse set of leadership skills, and as a Manager, you're a master of them all. In the store's fast-paced, dynamic Read more
*Apple* Solutions Consultant (ASC) - Apple (...
**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
*Apple* Retail - Market Leader - Cincinnati...
…challenges of developing individuals, building teams, and affecting growth across Apple Stores. You demonstrate successful leadership ability - focusing on excellence Read more
*Apple* Retail - Manager - SoHo - Apple (Uni...
Job SummaryKeeping an Apple Store thriving requires a diverse set of leadership skills, and as a Manager, you're a master of them all. In the store's fast-paced, dynamic Read more
Position Opening at *Apple* - Apple (United...
**Job Summary** Every day, business customers come to the Apple Store to discover what powerful, easy-to-use Apple products can do for them. As a Business Leader, Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.