Home > Articles > Software Development & Management > Object Technology

The Mechanics of COM+

If you want to apply COM+ successfully, you need to know more about how contexts work. This chapter from Transactional COM+ looks at the basic mechanics of contexts.
Like this article? We recommend

Atoms are complicated things, and the atoms of COM+ are no exception. This is particularly true of context, the mechanics of which are more complex than they appear at first glance. If you want to apply COM+ successfully, you need to know more about how contexts work. You need to understand the relationship between contexts and references to objects, that is, interface pointers. This association is integral to the correct behavior of the COM+ plumbing. You need to manage interface pointers properly for interception to work correctly. If you do not, interception will not work, and neither will any of the runtime services COM+ provides. You also need to understand the relationship between contexts and objects themselves. By default, every instance of every configured class gets a brand-new context of its own. This implies a nontrivial amount of overhead in both time (for interception) and space (for context data structures). Although you get runtime services in return, you should not simply accept these costs. You can reduce runtime overhead by creating multiple objects in a single context, but you need to know how to configure classes to exhibit this behavior. This chapter deals with these basic mechanical topics.

Context Relativity

COM+ does a lot of work to make sure new objects live in contexts configured to meet their needs. The goal, of course, is to make sure that when an object's method is invoked, it executes in an appropriate environment that provides the services the object requires. The details are handled by the interception plumbing, which "does the right thing" when a causality crosses a context boundary to do work against an object. While COM+ makes sure an object's environment is initially correct, you bear some responsibility for making sure it remains correct. To make sure the interception plumbing always works correctly, you have to treat interface pointers as context-relative resources that cannot be used outside the context where they were initially acquired. In general this is not a burden; however, in some rare circumstances it requires some extra work on your part.

The Problem

First, let me explain the problem. Remember that when a new object is created, the SCM has to decide whether it should exist in the same context as its creator or in a brand-new context of its own. In the former case CoCreateInstance[Ex] returns a raw interface pointer that refers to the new object directly. In the latter case it returns an interface pointer to a proxy set up to intercept each method call and provide whatever additional runtime services the new object requires.

Assume that the SCM decides a new object can exist in its creator's context and returns a raw reference to it, as shown in Figure 3-1. What would happen if the raw reference to the new object, A' in the diagram, were handed to an object in another context? Figure 3-2 depicts this situation. If the object in the foreign context, object B, were to call a method of object A' directly, no interception would occur. The method of object A' would execute in object B's environment, using whatever runtime services context B was configured to use. If the method of object A' attempted to access object context, the call to CoGetObjectContext would succeed, but it would return a reference to an object representing B's world. That is not at all what object A' expects. If object A' expects a declarative transaction, it might not get one or it might get object B's. Neither of these situations is good; in fact, either result could be catastrophic.

Figure 3-1
A new object in its creator's context

Figure 3-2
Raw reference passed across a context boundary

What happens if the SCM decides a new object needs to live in a new context and CoCreateInstance[Ex] returns a reference to a proxy, as shown in Figure 3-3? Does the same problem exist in this case? Can a reference to a proxy safely be handed to other contexts? The answers are yes, the problem remains, and no, the proxy cannot be used from other contexts. To understand why, you have to know a little bit more about the COM+ interception plumbing.

Figure 3-3
A new object in a new context

In Chapter 2, I explained that COM+ uses proxies to intercept cross-context calls and to "do the right thing" to provide the services' objects in the target context expect. Proxies, however, are just one part of the picture. The interception plumbing's logical model has three separate pieces, shown in Figure 3-4.

Figure 3-4
The logical architecture of the COM+ interception plumbing

A proxy represents an object in a foreign context. Proxies convert method calls into messages that can be sent through a channel. A channel is a conection to a foreign context, a pipe. Channels move messages from one context to another. A stub represents an object from a channel's point of view. Stubs convert messages back into method invocations on real objects. The physical structure of the interception plumbing differs depending on the distance between the two contexts it connects. Specifically, channels that move calls to other threads are more complex than channels that do not. Channels that do not move calls to other threads do not use full-blown stubs. Instead, the stub is merged with the channel. For simplicity's sake, the rest of this book focuses on the logical model of the interception plumbing and assumes there is always a stub.

COM+ runtime services are implemented in the stub side of the channel, where they can expose functionality as part of an object's context. (In some cases, such as just-in-time activation, the stub gets involved, too.) For example, if a declarative transaction is going to be made available as part of an object's environment, it makes no sense to try to do that on the proxy side. The declarative transaction has to be available to the real object, where it lives, not where the caller (and proxy) live. This architecture is shown in Figure 3-5.

Figure 3-5
 Runtime services are invoked by stub side of channel.

COM+ gains great flexibility by invoking runtime services in the channel instead of the stub. Each channel represents a connection to a stub from a particular proxy; there can be as many channels to a stub and object as required. Each proxy is permanently affixed to its channel when it is created. Stubs, on the other hand, are simply handed a channel long enough to process an inbound call. Within the scope of each call, the stub uses the channel to allocate memory for out parameters and to optimize their marshaling based on how far away the proxy is. COM+ tunes each channel's behavior so that it does the minimum amount of work necessary to bridge the difference between the proxy's context and the real object's context.

As Figure 3-6 illustrates, each channel is tuned to bridge the specific differences between its proxy's context and the real object's context. It might be, for instance, that calling from context A to context B mandates a security check and initiates a new declarative transaction, while calling from context C to context B initiates a new declarative transaction but does nothing in terms of security.

Figure 3-6
Multiple channels to the same object

What would happen if a reference to a proxy were handed to an object in another context, as shown in Figure 3-7? In this case, object C in context C holds a reference to the proxy in context A. Calls through the proxy will be intercepted, but because the proxy was created in context A, its channel cannot do the right thing. The channel's behavior is specifically optimized to deal with the difference between context A and context B. It knows nothing about context C. If calls from object C were allowed to go through, the results would be hard to predict and might be disastrous. So the channel does not let the call go through.

Figure 3-7
Proxy reference passed across context boundary

Channels actively enforce the context relativity of their proxies. The proxy side of the channel records the context it is initially created in. As each call comes in, the channel examines the current context ID, which is available as part of object context (remember IObjectContextInfo::GetContextId). If its original context ID and the current context ID match, the channel processes the call. If the IDs do not match, the channel returns a standard error code, RPC_E_WRONGTHREAD. COM+ inherited this constant from classic COM and uses it to indicate that a proxy is being used from a context other than its own, even if the problem has nothing to do with which thread is making the call. You should think of it as RPC_E_WRONGCONTEXT, which is what it really means.

You have to treat interface pointers as context-relative resources, or the interception plumbing will not work correctly. If you use a raw pointer to a real object in any context other than the one the object was created in, no interception will occur. If you use a pointer to a proxy in any context other than the one the proxy was created in, the channel will reject the call because it knows the right interception cannot occur. In either case, the resulting behavior is undesirable. In the former case, it is probably dangerous as well. All this leads to an inevitable question: How can you pass interface pointers to real objects or proxies from one context to another safely?

Marshaling Interface Pointers

Obviously COM+ has to provide a way to translate an interface pointer that is valid in one context into one that is valid in another context. If a pointer to a real object is passed to another context, it should be converted to a pointer to a proxy that is appropriate for that context and can forward calls back to the real object. If a pointer to a proxy is passed to another context, it should also be converted to a proxy appropriate for that context, with one exception. If a pointer to a proxy is passed to the context where the real object it refers to lives, the pointer to the proxy should be converted to a pointer to the real object instead.

COM+ enables all this functionality through an API it inherited from classic COM, CoMarshalInterface. CoMarshalInterface is one of a set of APIs designed to facilitate moving interface pointers from one context to another. CoMarshalInterface translates, or marshals, interface pointers into context-neutral byte streams called OBJREFs. An OBJREF contains the addressing information necessary to make calls back to an object. If you pass a pointer to a real object to CoMarshalInterface, it will create a stub for the object (if one does not already exist) and return an OBJREF identifying where the object lives. If you pass a pointer to a proxy to CoMarshalInterface, it will not create a stub, and it will return an OBJREF identifying where the real object the proxy refers to lives.

Once you have an OBJREF, you can take it to any context anywhere in the world and then convert it back into an interface pointer by calling CoUnmarshalInterface. CoUnmarshalInterface interprets, or unmarshals, the contents of an OBJREF and returns a pointer either to a proxy or to a real object if you happen to be in the context where the object the OBJREF refers to lives. If CoUnmarshalInterface returns a pointer to a proxy, the proxy is attached to a channel that is specifically tuned for the difference between the proxy's context and the real object's context.1

The context relativity of interface pointers is not a burden in general. You do not have to call these low-level plumbing APIs on a regular basis. Whenever you pass interface pointers to or receive them from the methods of COM interfaces or system APIs, you do not have to worry about marshaling; the plumbing takes care of all the details as needed. If you call CoCreateInstance[Ex] and the SCM decides the new object being created needs to live in a new context of its own, CoMarshalInterface and CoUnmarshalInterface are called automatically. If you pass an interface pointer through an existing proxy/stub connection, the proxy and stub call CoMarshalInterface and CoUnmarshal Interface on your behalf again. If you pass an interface pointer directly to an object in your own context, nothing happens because no translation is necessary. As long as you always pass interface pointers from one context to another using one of these techniques—COM APIs or the methods of COM interfaces—you never have to worry about marshaling interface pointers.

There are, however, two situations where you may want to pass interface pointers between contexts without using either a system API or a COM method call. First, you may want to put an interface pointer into a global variable that is accessible from multiple contexts in your process. Second, you may want to pass an interface pointer to a new thread you are starting. These are the rare circumstances where you have to do some extra work. In both these cases, you are responsible for making sure interface pointers are marshaled correctly.

The Global Interface Table

Even when you are responsible for marshaling interface pointers by hand, you do not have to use the low-level marshaling APIs. Most application developers use the Global Interface Table (GIT) instead. The GIT is a processwide lookup table that maps back and forth between context-relative interface pointers and context-neutral cookies. The GIT is implemented in OLE32.DLL. You can instantiate it by calling CoCreateInstance[Ex] and passing CLSID_Std GlobalInterfaceTable. A reference to the GIT is implicitly context neutral. It can be cached in a global variable and safely accessed from any context. This is a special exception to the context-relativity rule that does not apply in the general case. Figure 3-8 shows the architecture of the GIT.

Figure 3-8
The Global Interface Table

The Global Interface Table implements a standard interface called GlobalInterfaceTable.

interface IGlobalInterfaceTable : IUnknown
{
 HRESULT RegisterInterfaceInGlobal([in] IUnknown *pUnk,
                  [in] REFIID riid,
                  [out] DWORD *pdwCookie);
 HRESULT RevokeInterfaceFromGlobal([in] DWORD dwCookie);
 HRESULT GetInterfaceFromGlobal([in] DWORD dwCookie,
                 [in] REFIID riid,
                 [out, iid_is(riid)] void **ppv);
};

RegisterInterfaceInGlobal inserts an interface pointer into the GIT and returns a context-neutral cookie to represent it. The cookie is a DWORD that is guaranteed not to be 0 (the null cookie, like a null pointer, is never valid). A GIT cookie can be passed to another context using any technique you like, including via a global variable or as an argument to a new thread. GetInterfaceFromGlobal converts a valid cookie into an interface pointer that is appropriate for the current context. A cookie remains valid until the interface pointer it refers to is removed from the GIT by a call to RevokeInterfaceFromGlobal. This explicit clean-up mechanism allows the GIT to easily support a "marshal-once/unmarshal-many times" scheme, which is preferred if you're going to store a GIT cookie in a global variable. It also means that the GIT holds a reference to a registered object until it is explicitly revoked. If you fail to revoke a reference held by the GIT, the object it refers to will remain in memory until the GIT releases it when the process shuts down.

Here is an example demonstrating how the GIT can be used to pass an interface pointer to a new thread. The StartSomething function creates a new object and passes it as input to a new thread. It uses the GIT to marshal the interface pointer.

// Global GIT reference initialized elsewhere
extern IGlobalInterfaceTable *g_pGIT;
// Declaration of thread proc implemented below
DWORD WINAPI DoSomething(void *pv);
// Function that starts a new thread
HRESULT StartSomething(void)
{
 // Create new object
 CComPtr<IObject> spObj;
 HRESULT hr = spObj.CoCreateInstance(__uuidof(SomeObject));
 if (FAILED(hr)) return hr;
 // Put reference to object into GIT
 DWORD cookie = 0;
 hr = g_pGIT->RegisterInterfaceInGlobal(spObj, __uuidof(spObj),
                     &cookie);
 if (FAILED(hr)) return hr;
 // Start new thread, passing cookie as argument
 HANDLE thread = CreateThread(0, 0, &DoSomething,
                (void*)cookie, 0, 0); 
 // If CreateThread fails, remove reference from GIT
 if (thread == 0)
 {
  g_pGIT->RevokeInterfaceFromGlobal(dwCookie);
  return E_FAIL;
 }
 CloseHandle(thread);
 return hr;
}

Notice that this function removes the interface pointer from the GIT if CreateThread fails. Here is the implementation of the thread function, DoSomething. It uses the cookie that StartSomething passed as an input argument to retrieve an interface pointer to the object from the GIT.

// implementation of thread proc
DWORD WINAPI DoSomething(void *pv)
{
 // initialize COM
 HRESULT hr = CoInitializeEx(0, COINIT_MULTITHREADED);
 if (FAILED(hr)) return hr;
 // retrieve reference from GIT
 DWORD cookie = (DWORD) pv;
 CComPtr<IObject> spObj;
 hr = g_pGIT->GetInterfaceFromGlobal(cookie, __uuidof(spObj),
                   (void**)&spObj);
 // remove reference from GIT
 g_pGIT->RevokeInterfaceFromGlobal(cookie);
 // if attempt to get reference failed, exit
 if (FAILED(hr)) return hr;
 ... // use object
 // clean things up
 spObj.Release();
 CoUninitialize();
 return hr;
}

This function retrieves an interface pointer to the object and then removes it from the GIT. When this thread function completes, the object is released.

Context Relativity in Day-to-Day Life

Although you have to be aware of context relativity and the importance of marshaling interface pointers between contexts, you typically do not have to spend much time worrying about these issues in your day-to-day development work. None of the code in Chapter 1 had to worry about context relativity at all. COM+ designs are based on the object-per-client model (remember Rule 1.1), so it is unlikely that you will need to put an interface pointer into a global variable. Similarly COM+-based classes typically rely on the thread pool provided by the runtime and do not create their own threads. Still, there may be cases where you want to share an interface pointer using one of these techniques, especially if you are building some relatively low-level plumbing of your own, an efficient middle-tier cache, for example. There may also be situations where you violate context relativity accidentally and need to be able to figure out why your code is not working correctly. Just remember that context relativity boils down to one simple, tremendously important guideline, Rule 3.1. If you do not follow this rule, the interception plumbing and, therefore, the context programming model will not work correctly.


Rule 3.1

Do not pass interface pointers from one context to another without using a system-provided facility (e.g., system API, COM interface method, the Global Interface Table) to translate the reference to work in the destination context.


Footnotes

1. My coverage of this topic is purposefully brief because, although this aspect of the plumbing is important to understand, the details are not relevant to this story and have been copiously documented elsewhere. For more information on these APIs and the contents of OBJREFs, see the COM Specification and the DCOM Protocol Internet Draft, available from MSDN or online at http://www.microsoft.com/com/, or Essential COM by Box.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020