Previous Up Next

Chapter 2  The Basics

In this chapter, we go through three examples to illustrate the practical steps to use omniORB. By going through the source code of each example, the essential concepts and APIs are introduced. If you have no previous experience with using CORBA, you should study this chapter in detail. There are pointers to other essential documents you should be familiar with.

If you have experience with using other ORBs, you should still go through this chapter because it provides important information about the features and APIs that are necessarily omniORB specific. With the Portable Object Adapter, there are very few omniORB specific details.

2.1  The Echo Object Example

Our example is an object which has only one method. The method simply echos the argument string. We have to:

  1. define the object interface in IDL;
  2. use the IDL compiler to generate the stub code1;
  3. provide the servant object implementation;
  4. write the client code.

These examples are in the src/examples/echo directory of the omniORB distribution; there are several other examples one directory above that in src/examples.

2.2  Specifying the Echo interface in IDL

We define an object interface, called Echo, as follows:

interface Echo { string echoString(in string mesg); };

If you are new to IDL, you can learn about its syntax in Chapter 3 of the CORBA 2.6 specification [OMG01]. For the moment, you only need to know that the interface consists of a single operation, echoString(), which takes a string as an input argument and returns a copy of the same string.

The interface is written in a file, called echo.idl. It is part of the CORBA standard that all IDL files should have the extension ‘.idl’, although omniORB does not enforce this.

For simplicity, the interface is defined in the global IDL namespace. You should avoid this practice for the sake of object reusability. If every CORBA developer defines their interfaces in the global IDL namespace, there is a danger of name clashes between two independently defined interfaces. Therefore, it is better to qualify your interfaces by defining them inside module names. Of course, this does not eliminate the chance of a name clash unless some form of naming convention is agreed globally. Nevertheless, a well-chosen module name can help a lot.

2.3  Generating the C++ stubs

From the IDL file, we use the IDL compiler to produce the C++ mapping of the interface. The IDL compiler for omniORB is called omniidl. Given the IDL file, omniidl produces two stub files: a C++ header file and a C++ source file. For example, from the file echo.idl, the following files are produced:

omniidl must be invoked with the -bcxx argument to tell it to generate C++ stubs. The following command line generates the stubs for echo.idl:

omniidl -bcxx echo.idl

If you are using our make environment (ODE), you don’t need to invoke omniidl explicitly. In the example file dir.mk, we have the following line:

CORBA_INTERFACES = echo

That is all we need to instruct ODE to generate the stubs. Remember, you won’t find the stubs in your working directory because all stubs are written into the stub directory at the top level of your build tree.

The full arguments to omniidl are detailed in chapter 5.

2.4  Object References and Servants

We contact a CORBA object through an object reference. The actual implementation of a CORBA object is termed a servant.

Object references and servants are quite separate entities, and it is important not to confuse the two. Client code deals purely with object references, so there can be no confusion; object implementation code must deal with both object references and servants. omniORB 4 uses distinct C++ types for object references and servants, so the C++ compiler will complain if you use a servant when an object reference is expected, or vice-versa.


Warning

omniORB 2.x did not use distinct types for object references and servants, and often accepted a pointer to a servant when the CORBA specification says it should only accept an object reference. If you have code which relies on this, it will not compile with omniORB 3.x or 4.x, even under the BOA compatibility mode.


2.5  A Quick Tour of the C++ stubs

The C++ stubs conform to the standard mapping defined in the CORBA specification [OMG03]. It is important to understand the mapping before you start writing any serious CORBA applications. Before going any further, it is worth knowing what the mapping looks like.

For the example interface Echo, the C++ mapping for its object reference is Echo_ptr. The type is defined in echo.hh. The relevant section of the code is reproduced below. The stub code produced by other ORBs will be functionally equivalent to omniORB’s, but will almost certainly look very different.

class Echo; class _objref_Echo; class _impl_Echo; typedef _objref_Echo* Echo_ptr; class Echo { public: // Declarations for this interface type. typedef Echo_ptr _ptr_type; typedef Echo_var _var_type; static _ptr_type _duplicate(_ptr_type); static _ptr_type _narrow(CORBA::Object_ptr); static _ptr_type _nil(); // ... methods generated for internal use }; class _objref_Echo : public virtual CORBA::Object, public virtual omniObjRef { public: char * echoString(const char* mesg); // ... methods generated for internal use };

In a compliant application, the operations defined in an object interface should only be invoked via an object reference. This is done by using arrow (‘->’) on an object reference. For example, the call to the operation echoString() would be written as obj->echoString(mesg).

It should be noted that the concrete type of an object reference is opaque, i.e. you must not make any assumption about how an object reference is implemented. In our example, even though Echo_ptr is implemented as a pointer to the class _objref_Echo, it should not be used as a C++ pointer, i.e. conversion to void*, arithmetic operations, and relational operations including testing for equality using operator==, must not be performed on the type.

In addition to class _objref_Echo, the mapping defines three static member functions in the class Echo: _nil(), _duplicate(), and _narrow().

The _nil() function returns a nil object reference of the Echo interface. The following call is guaranteed to return TRUE:

CORBA::Boolean true_result = CORBA::is_nil(Echo::_nil());

Remember, CORBA::is_nil() is the only compliant way to check if an object reference is nil. You should not use the equality operator==. Many C++ ORBs use the null pointer to represent a nil object reference; omniORB does not.

The _duplicate() function returns a new object reference of the Echo interface. The new object reference can be used interchangeably with the old object reference to perform an operation on the same object. Duplications are required to satisfy the C++ mapping’s reference counting memory management.

All CORBA objects inherit from the generic object CORBA::Object. CORBA::Object_ptr is the object reference type for CORBA::Object. Any _ptr object reference is therefore conceptually inherited from CORBA::Object_ptr. In other words, an object reference such as Echo_ptr can be used in places where a CORBA::Object_ptr is expected.

The _narrow() function takes an argument of type CORBA::Object_ptr and returns a new object reference of the Echo interface. If the actual (runtime) type of the argument object reference can be narrowed to Echo_ptr, _narrow() will return a valid object reference. Otherwise it will return a nil object reference. Note that _narrow() performs an implicit duplication of the object reference, so the result must be released. Note also that _narrow() may involve a remote call to check the type of the object, so it may throw CORBA system exceptions such as COMM_FAILURE or OBJECT_NOT_EXIST.

To indicate that an object reference will no longer be accessed, you must call the CORBA::release() operation. Its signature is as follows:

namespace CORBA { void release(CORBA::Object_ptr obj); ... // other methods };

Once you have called CORBA::release() on an object reference, you must no longer use that reference. This is because the associated resources may have been deallocated. Notice that we are referring to the resources associated with the object reference and not the servant object. Servant objects are not affected by the lifetimes of object references. In particular, servants are not deleted when all references to them have been released—CORBA does not perform distributed garbage collection.

As described above, the equality operator== should not be used on object references. To test if two object references are equivalent, the member function _is_equivalent() of the generic object CORBA::Object can be used. Here is an example of its usage:

Echo_ptr A; ... // initialise A to a valid object reference Echo_ptr B = A; CORBA::Boolean true_result = A->_is_equivalent(B); // Note: the above call is guaranteed to be TRUE

You have now been introduced to most of the operations that can be invoked via Echo_ptr. The generic object CORBA::Object provides a few more operations and all of them can be invoked via Echo_ptr. These operations deal mainly with CORBA’s dynamic interfaces. You do not have to understand them in order to use the C++ mapping provided via the stubs.

Since object references must be released explicitly, their usage is prone to error and can lead to memory leakage. The mapping defines the object reference variable type to make life easier. In our example, the variable type Echo_var is defined2.

The Echo_var is more convenient to use because it will automatically release its object reference when it is deallocated or when assigned a new object reference. For many operations, mixing data of type Echo_var and Echo_ptr is possible without any explicit operations or castings3. For instance, the operation echoString() can be called using the arrow (‘->’) on a Echo_var, as one can do with a Echo_ptr.

The usage of Echo_var is illustrated below:

Echo_var a; Echo_ptr p = ... // somehow obtain an object reference a = p; // a assumes ownership of p, must not use p any more Echo_var b = a; // implicit _duplicate p = ... // somehow obtain another object reference a = Echo::_duplicate(p); // release old object reference // a now holds a copy of p.

2.5.1  Servant Object Implementation

Before the Portable Object Adapter (POA) specification, many of the details of how servant objects should be implemented and registered with the system were unspecified, so server-side code was not portable between ORBs. The POA specification rectifies that. omniORB 4 still supports the old omniORB 2.x BOA mapping, but you should always use the POA mapping for new code. BOA code and POA code can coexist within a single program. See section 3.1 for details of the BOA compatibility, and problems you may encounter.

For each object interface, a skeleton class is generated. In our example, the POA specification says that the skeleton class for interface Echo is named POA_Echo. A servant implementation can be written by creating an implementation class that derives from the skeleton class.

The skeleton class POA_Echo is defined in echo.hh. The relevant section of the code is reproduced below.

class POA_Echo : public virtual PortableServer::ServantBase { public: Echo_ptr _this(); virtual char * echoString(const char* mesg) = 0; // ... };

The code fragment shows the only member functions that can be used in the object implementation code. Other member functions are generated for internal use only. As with the code generated for object references, other POA-based ORBs will generate code which looks different, but is functionally equivalent to this.

echoString()

It is through this abstract function that an implementation class provides the implementation of the echoString() operation. Notice that its signature is the same as the echoString() function that can be invoked via the Echo_ptr object reference.
_this()

This function returns an object reference for the target object, provided the POA policies permit it. The returned value must be deallocated via CORBA::release(). See section 2.8 for an example of how this function is used.

2.6  Writing the servant implementation

You define an implementation class to provide the servant implementation. There is little constraint on how you design your implementation class except that it has to inherit from the stubs’ skeleton class and to implement all the abstract functions defined in the skeleton class. Each of these abstract functions corresponds to an operation of the interface. They are the hooks for the ORB to perform upcalls to your implementation.

Here is a simple implementation of the Echo object.

class Echo_i : public POA_Echo { public: inline Echo_i() {} virtual ~Echo_i() {} virtual char* echoString(const char* mesg); }; char* Echo_i::echoString(const char* mesg) { return CORBA::string_dup(mesg); }

There are four points to note here:

Storage Responsibilities

A string, which is used both as an in argument and the return value of echoString(), is a variable size data type. Other examples of variable size data types include sequences, type ‘any’, etc. For these data types, you must be clear about whose responsibility it is to allocate and release the associated storage. As a rule of thumb, the client (or the caller to the implementation functions) owns the storage of all IN arguments, the object implementation (or the callee) must copy the data if it wants to retain a copy. For OUT arguments and return values, the object implementation allocates the storage and passes the ownership to the client. The client must release the storage when the variables will no longer be used. For details, please refer to the C++ mapping specification.
Multi-threading

As omniORB is fully multithreaded, multiple threads may perform the same upcall to your implementation concurrently. It is up to your implementation to synchronise the threads’ accesses to shared data. In our simple example, we have no shared data to protect so no thread synchronisation is necessary.

Alternatively, you can create a POA which has the SINGLE_THREAD_MODEL Thread Policy. This guarantees that all calls to that POA are processed sequentially.

Reference Counting

All servant objects are reference counted. The base PortableServer::ServantBase class from which all servant skeleton classes derive defines member functions named _add_ref() and _remove_ref()4. The reference counting means that an Echo_i instance will be deleted when no more references to it are held by application code or the POA itself. Note that this is totally separate from the reference counting which is associated with object references—a servant object is never deleted due to a CORBA object reference being released.
Instantiation

Servants are usually instantiated on the heap, i.e. using the new operator. However, they can also be created on the stack as automatic variables. If you do that, it is vital to make sure that the servant has been deactivated, and thus released by the POA, before the variable goes out of scope and is destroyed.

2.7  Writing the client

Here is an example of how an Echo_ptr object reference is used.

1 void 2 hello(CORBA::Object_ptr obj) 3 { 4 Echo_var e = Echo::_narrow(obj); 5 6 if (CORBA::is_nil(e)) { 7 cerr << "cannot invoke on a nil object reference." 8 << endl; 9 return; 10 } 11 12 CORBA::String_var src = (const char*) "Hello!"; 13 CORBA::String_var dest; 14 15 dest = e->echoString(src); 16 17 cerr << "I said,\"" << src << "\"." 18 << " The Object said,\"" << dest <<"\"" << endl; 19 }

Briefly, the hello() function accepts a generic object reference. The object reference (obj) is narrowed to Echo_ptr. If the object reference returned by Echo::_narrow() is not nil, the operation echoString() is invoked. Finally, both the argument to and the return value of echoString() are printed to cerr.

The example also illustrates how T_var types are used. As was explained in the previous section, T_var types take care of storage allocation and release automatically when variables are reassigned or when the variables go out of scope.

In line 4, the variable e takes over the storage responsibility of the object reference returned by Echo::_narrow(). The object reference is released by the destructor of e. It is called automatically when the function returns. Lines 6 and 15 show how a Echo_var variable is used. As explained earlier, the Echo_var type can be used interchangeably with the Echo_ptr type.

The argument and the return value of echoString() are stored in CORBA::String_var variables src and dest respectively. The strings managed by the variables are deallocated by the destructor of CORBA::String_var. It is called automatically when the variable goes out of scope (as the function returns). Line 15 shows how CORBA::String_var variables are used. They can be used in place of a string (for which the mapping is char*)5. As used in line 12, assigning a constant string (const char*) to a CORBA::String_var causes the string to be copied. On the other hand, assigning a char* to a CORBA::String_var, as used in line 15, causes the latter to assume the ownership of the string6.

Under the C++ mapping, T_var types are provided for all the non-basic data types. It is obvious that one should use automatic variables whenever possible both to avoid memory leaks and to maximise performance. However, when one has to allocate data items on the heap, it is a good practice to use the T_var types to manage the heap storage.

2.8  Example 1 — Colocated Client and Implementation

Having introduced the client and the object implementation, we can now describe how to link up the two via the ORB and POA. In this section, we describe an example in which both the client and the object implementation are in the same address space. In the next two sections, we shall describe the case where the two are in different address spaces.

The code for this example is reproduced below:

1 int 2 main(int argc, char **argv) 3 { 4 CORBA::ORB_ptr orb = CORBA::ORB_init(argc,argv,"omniORB4"); 5 6 CORBA::Object_var obj = orb->resolve_initial_references("RootPOA"); 7 PortableServer::POA_var poa = PortableServer::POA::_narrow(obj); 8 9 Echo_i *myecho = new Echo_i(); 10 PortableServer::ObjectId_var myechoid = poa->activate_object(myecho); 11 12 Echo_var myechoref = myecho->_this(); 13 myecho->_remove_ref(); 14 15 PortableServer::POAManager_var pman = poa->the_POAManager(); 16 pman->activate(); 17 18 hello(myechoref); 19 20 orb->destroy(); 21 return 0; 22 }

The example illustrates several important interactions among the ORB, the POA, the servant, and the client. Here are the details:

2.8.1  ORB initialisation

Line 4

The ORB is initialised by calling the CORBA::ORB_init() function. The function uses the optional 3rd argument to determine which ORB should be returned. Unless you are using omniORB specific features, it is usually best to leave it out, and get the default ORB. To explicitly ask for omniORB 4.x, this argument must be ‘omniORB4’7.

CORBA::ORB_init() takes the list of command line arguments and processes any that start ‘-ORB’. It removes these arguments from the list, so application code does not have to deal with them.

If any error occurs during ORB initialisation, such as invalid ORB arguments, or an invalid configuration file, the CORBA::INITIALIZE system exception is raised.

2.8.2  Obtaining the Root POA

Lines 6–7

To activate our servant object and make it available to clients, we must register it with a POA. In this example, we use the Root POA, rather than creating any child POAs. The Root POA is found with orb->resolve_initial_references(), which returns a plain CORBA::Object. In line 7, we narrow the reference to the right type for a POA.

A POA’s behaviour is governed by its policies. The Root POA has suitable policies for many simple servers, and closely matches the ‘policies’ used by omniORB 2’s BOA. See Chapter 11 of the CORBA 2.6 specification[OMG01] for details of all the POA policies which are available.

2.8.3  Object initialisation

Line 9

An instance of the Echo servant is initialised using the new operator.
Line 10

The servant object is activated in the Root POA using poa->activate_object(), which returns an object identifier (of type PortableServer::ObjectId*). The object id must be passed back to various POA operations. The caller is responsible for freeing the object id, so it is assigned to a _var type.
Line 12

The object reference is obtained from the servant object by calling _this(). Like all object references, the return value of _this() must be released by CORBA::release() when it is no longer needed. In this case, we assign it to a _var type, so the release is implicit at the end of the function.

One of the important characteristics of an object reference is that it is completely location transparent. A client can invoke on the object using its object reference without any need to know whether the servant object is colocated in the same address space or is in a different address space.

In the case of colocated client and servant, omniORB is able to short-circuit the client calls so they do not involve IIOP. The calls still go through the POA, however, so the various POA policies affect local calls in the same way as remote ones. This optimisation is applicable not only to object references returned by _this(), but to any object references that are passed around within the same address space or received from other address spaces via remote calls.

Line 13

The server code releases the reference it holds to the servant object. The only reference to that object is now held by the POA (it gained the reference on the call to activate_object()), so when the object is deactivated (or the POA is destroyed), the servant object will be deleted automatically. After this point, the code must no longer use the myecho pointer.

2.8.4  Activating the POA

Lines 15–16

POAs are initially in the holding state, meaning that incoming requests are blocked. Lines 15 and 16 acquire a reference to the POA’s POA manager, and use it to put the POA into the active state. Incoming requests are now served. Failing to activate the POA is one of the most common programming mistakes. If your program appears deadlocked, make sure you activated the POA!

2.8.5  Performing a call

Line 18

At long last, we can call hello() with this object reference. The argument is widened implicitly to the generic object reference CORBA::Object_ptr.

2.8.6  ORB destruction

Line 20

Shutdown the ORB permanently. This call causes the ORB to release all its resources, e.g. internal threads, and also to deactivate any servant objects which are currently active. When it deactivates the Echo_i instance, the servant’s reference count drops to zero, so the servant is deleted.

This call is particularly important when writing a CORBA DLL on Windows NT that is to be used from ActiveX. If this call is absent, the application will hang when the CORBA DLL is unloaded.

2.9  Example 2 — Different Address Spaces

In this example, the client and the object implementation reside in two different address spaces. The code of this example is almost the same as the previous example. The only difference is the extra work which needs to be done to pass the object reference from the object implementation to the client.

The simplest (and quite primitive) way to pass an object reference between two address spaces is to produce a stringified version of the object reference and to pass this string to the client as a command-line argument. The string is then converted by the client into a proper object reference. This method is used in this example. In the next example, we shall introduce a better way of passing the object reference using the CORBA Naming Service.

2.9.1  Object Implementation: Making a Stringified Object Reference

The main() function of the server side is reproduced below. The full listing (eg2_impl.cc) can be found at the end of this chapter.

1 int main(int argc, char** argv) 2 { 3 CORBA::ORB_var orb = CORBA::ORB_init(argc, argv); 4 5 CORBA::Object_var obj = orb->resolve_initial_references("RootPOA"); 6 PortableServer::POA_var poa = PortableServer::POA::_narrow(obj); 7 8 Echo_i* myecho = new Echo_i(); 9 10 PortableServer::ObjectId_var myechoid = poa->activate_object(myecho); 11 12 obj = myecho->_this(); 13 CORBA::String_var sior(orb->object_to_string(obj)); 14 cerr << (char*)sior << endl; 15 16 myecho->_remove_ref(); 17 18 PortableServer::POAManager_var pman = poa->the_POAManager(); 19 pman->activate(); 20 21 orb->run(); 22 orb->destroy(); 23 return 0; 24 }

The stringified object reference is obtained by calling the ORB’s object_to_string() function (line 13). This results in a string starting with the signature ‘IOR:’ and followed by some hexadecimal digits. All CORBA 2 compliant ORBs are able to convert the string into its internal representation of a so-called Interoperable Object Reference (IOR). The IOR contains the location information and a key to uniquely identify the object implementation in its own address space. From the IOR, an object reference can be constructed.

2.9.2  Client: Using a Stringified Object Reference

The stringified object reference is passed to the client as a command-line argument. The client uses the ORB’s string_to_object() function to convert the string into a generic object reference (CORBA::Object_ptr). The relevant section of the code is reproduced below. The full listing (eg2_clt.cc) can be found at the end of this chapter.

try { CORBA::Object_var obj = orb->string_to_object(argv[1]); hello(obj); } catch(CORBA::TRANSIENT&) { ... // code to handle transient exception... }

2.9.3  Catching System Exceptions

When omniORB detects an error condition, it may raise a system exception. The CORBA specification defines a series of exceptions covering most of the error conditions that an ORB may encounter. The client may choose to catch these exceptions and recover from the error condition8. For instance, the code fragment, shown in section 2.9.2, catches the TRANSIENT system exception which indicates that the object could not be contacted at the time of the call, usually meaning the server is not running.

All system exceptions inherit from CORBA::SystemException. With compilers that properly support RTTI9, a single catch of CORBA::SystemException will catch all the different system exceptions thrown by omniORB.

When omniORB detects an internal error such as corrupt data or invalid conditions, it raises the exception omniORB::fatalException. When this exception is raised, it is not sensible to proceed with any operation that involves the ORB’s runtime. It is best to exit the program immediately. The exception structure carried by omniORB::fatalException contains the exact location (the file name and the line number) where the exception is raised. In most cases, fatalExceptions occur due to incorrect behaviour by the application code, but they may be caused by bugs in omniORB.

2.9.4  Lifetime of a CORBA object

CORBA objects are either transient or persistent. The majority are transient, meaning that the lifetime of the CORBA object (as contacted through an object reference) is the same as the lifetime of its servant object. Persistent objects can live beyond the destruction of their servant object, the POA they were created in, and even their process. Persistent objects are, of course, only contactable when their associated servants are active, or can be activated by their POA with a servant manager10. A reference to a persistent object can be published, and will remain valid even if the server process is restarted.

A POA’s Lifespan Policy determines whether objects created within it are transient or persistent. The Root POA has the TRANSIENT policy.

An alternative to creating persistent objects is to register object references in a naming service and bind them to fixed path names. Clients can bind to the object implementations at run time by asking the naming service to resolve the path names to the object references. CORBA defines a standard naming service, which is a component of the Common Object Services (COS) [OMG98], that can be used for this purpose. The next section describes an example of how to use the COS Naming Service.

2.10  Example 3 — Using the Naming Service

In this example, the object implementation uses the Naming Service [OMG98] to pass on the object reference to the client. This method is far more practical than using stringified object references. The full listing of the object implementation (eg3_impl.cc) and the client (eg3_clt.cc) can be found at the end of this chapter.

The names used by the Naming service consist of a sequence of name components. Each name component has an id and a kind field, both of which are strings. All name components except the last one are bound to a naming context. A naming context is analogous to a directory in a filing system: it can contain names of object references or other naming contexts. The last name component is bound to an object reference.

Sequences of name components can be represented as a flat string, using ‘.’ to separate the id and kind fields, and ‘/’ to separate name components from each other11. In our example, the Echo object reference is bound to the stringified name ‘test.my_context/Echo.Object’.

The kind field is intended to describe the name in a syntax-independent way. The naming service does not interpret, assign, or manage these values. However, both the name and the kind attribute must match for a name lookup to succeed. In this example, the kind values for test and Echo are chosen to be ‘my_context’ and ‘Object’ respectively. This is an arbitrary choice as there is no standardised set of kind values.

2.10.1  Obtaining the Root Context Object Reference

The initial contact with the Naming Service can be established via the root context. The object reference to the root context is provided by the ORB and can be obtained by calling resolve_initial_references(). The following code fragment shows how it is used:

CORBA::ORB_ptr orb = CORBA::ORB_init(argc,argv); CORBA::Object_var initServ; initServ = orb->resolve_initial_references("NameService"); CosNaming::NamingContext_var rootContext; rootContext = CosNaming::NamingContext::_narrow(initServ);

Remember, omniORB constructs its internal list of initial references at initialisation time using the information provided in the configuration file omniORB.cfg, or given on the command line. If this file is not present, the internal list will be empty and resolve_initial_references() will raise a CORBA::ORB::InvalidName exception.

2.10.2  The Naming Service Interface

It is beyond the scope of this chapter to describe in detail the Naming Service interface. You should consult the CORBA services specification [OMG98] (chapter 3). The code listed in eg3_impl.cc and eg3_clt.cc are good examples of how the service can be used. Please spend time to study the examples carefully.

2.11  Example 4 — Using tie implementation templates

omniORB supports tie implementation templates as an alternative way of providing servant classes. If you use the -Wbtp option to omniidl, it generates an extra template class for each interface. This template class can be used to tie a C++ class to the skeleton class of the interface.

The source code in eg3_tieimpl.cc at the end of this chapter illustrates how the template class can be used. The code is almost identical to eg3_impl.cc with only a few changes.

Firstly, the servant class Echo_i does not inherit from any stub classes. This is the main benefit of using the template class because there are applications in which it is difficult to require every servant class to derive from CORBA classes.

Secondly, the instantiation of a CORBA object now involves creating an instance of the implementation class and an instance of the template. Here is the relevant code fragment:

class Echo_i { ... }; Echo_i *myimpl = new Echo_i(); POA_Echo_tie<Echo_i> myecho(myimpl); PortableServer::ObjectId_var myechoid = poa->activate_object(&myecho);

For interface Echo, the name of its tie implementation template is POA_Echo_tie. The template parameter is the servant class that contains an implementation of each of the operations defined in the interface. As used above, the tie template takes ownership of the Echo_i instance, and deletes it when the tie object goes out of scope. The tie constructor has an optional boolean argument (defaulted to true) which indicates whether or not it should delete the servant object. For full details of using tie templates, see the CORBA C++ mapping specification.

2.12  Source Listings

2.12.1  eg1.cc

// eg1.cc - This is the source code of example 1 used in Chapter 2 // "The Basics" of the omniORB user guide. // // In this example, both the object implementation and the // client are in the same process. // // Usage: eg1 // #include <echo.hh> #ifdef HAVE_STD # include <iostream> using namespace std; #else # include <iostream.h> #endif // This is the object implementation. class Echo_i : public POA_Echo { public: inline Echo_i() {} virtual ~Echo_i() {} virtual char* echoString(const char* mesg); }; char* Echo_i::echoString(const char* mesg) { return CORBA::string_dup(mesg); } ////////////////////////////////////////////////////////////////////// // This function acts as a client to the object. static void hello(Echo_ptr e) { if( CORBA::is_nil(e) ) { cerr << "hello: The object reference is nil!\n" << endl; return; } CORBA::String_var src = (const char*) "Hello!"; // String literals are (char*) rather than (const char*) on some // old compilers. Thus it is essential to cast to (const char*) // here to ensure that the string is copied, so that the // CORBA::String_var does not attempt to 'delete' the string // literal. CORBA::String_var dest = e->echoString(src); cout << "I said, \"" << (char*)src << "\"." << endl << "The Echo object replied, \"" << (char*)dest <<"\"." << endl; } ////////////////////////////////////////////////////////////////////// int main(int argc, char** argv) { try { // Initialise the ORB. CORBA::ORB_var orb = CORBA::ORB_init(argc, argv); // Obtain a reference to the root POA. CORBA::Object_var obj = orb->resolve_initial_references("RootPOA"); PortableServer::POA_var poa = PortableServer::POA::_narrow(obj); // We allocate the object on the heap. Since this is a reference // counted object, it will be deleted by the POA when it is no // longer needed. Echo_i* myecho = new Echo_i(); // Activate the object. This tells the POA that this object is // ready to accept requests. PortableServer::ObjectId_var myechoid = poa->activate_object(myecho); // Obtain a reference to the object. Echo_var myechoref = myecho->_this(); // Decrement the reference count of the object implementation, so // that it will be properly cleaned up when the POA has determined // that it is no longer needed. myecho->_remove_ref(); // Obtain a POAManager, and tell the POA to start accepting // requests on its objects. PortableServer::POAManager_var pman = poa->the_POAManager(); pman->activate(); // Do the client-side call. hello(myechoref); // Clean up all the resources. orb->destroy(); } catch(CORBA::SystemException& ex) { cerr << "Caught CORBA::" << ex._name() << endl; } catch(CORBA::Exception& ex) { cerr << "Caught CORBA::Exception: " << ex._name() << endl; } catch(omniORB::fatalException& fe) { cerr << "Caught omniORB::fatalException:" << endl; cerr << " file: " << fe.file() << endl; cerr << " line: " << fe.line() << endl; cerr << " mesg: " << fe.errmsg() << endl; } return 0; }

2.12.2  eg2_impl.cc

// eg2_impl.cc - This is the source code of example 2 used in Chapter 2 // "The Basics" of the omniORB user guide. // // This is the object implementation. // // Usage: eg2_impl // // On startup, the object reference is printed to cerr as a // stringified IOR. This string should be used as the argument to // eg2_clt. // #include <echo.hh> #ifdef HAVE_STD # include <iostream> using namespace std; #else # include <iostream.h> #endif class Echo_i : public POA_Echo { public: inline Echo_i() {} virtual ~Echo_i() {} virtual char* echoString(const char* mesg); }; char* Echo_i::echoString(const char* mesg) { cout << "Upcall " << mesg << endl; return CORBA::string_dup(mesg); } ////////////////////////////////////////////////////////////////////// int main(int argc, char** argv) { try { CORBA::ORB_var orb = CORBA::ORB_init(argc, argv); CORBA::Object_var obj = orb->resolve_initial_references("RootPOA"); PortableServer::POA_var poa = PortableServer::POA::_narrow(obj); Echo_i* myecho = new Echo_i(); PortableServer::ObjectId_var myechoid = poa->activate_object(myecho); // Obtain a reference to the object, and print it out as a // stringified IOR. obj = myecho->_this(); CORBA::String_var sior(orb->object_to_string(obj)); cout << (char*)sior << endl; myecho->_remove_ref(); PortableServer::POAManager_var pman = poa->the_POAManager(); pman->activate(); orb->run(); } catch(CORBA::SystemException& ex) { cerr << "Caught CORBA::" << ex._name() << endl; } catch(CORBA::Exception& ex) { cerr << "Caught CORBA::Exception: " << ex._name() << endl; } catch(omniORB::fatalException& fe) { cerr << "Caught omniORB::fatalException:" << endl; cerr << " file: " << fe.file() << endl; cerr << " line: " << fe.line() << endl; cerr << " mesg: " << fe.errmsg() << endl; } return 0; }

2.12.3  eg2_clt.cc

// eg2_clt.cc - This is the source code of example 2 used in Chapter 2 // "The Basics" of the omniORB user guide. // // This is the client. The object reference is given as a // stringified IOR on the command line. // // Usage: eg2_clt <object reference> // #include <echo.hh> #ifdef HAVE_STD # include <iostream> # include <fstream> using namespace std; #else # include <iostream.h> #endif static void hello(Echo_ptr e) { CORBA::String_var src = (const char*) "Hello!"; CORBA::String_var dest = e->echoString(src); cout << "I said, \"" << (char*)src << "\"." << endl << "The Echo object replied, \"" << (char*)dest <<"\"." << endl; } ////////////////////////////////////////////////////////////////////// int main(int argc, char** argv) { try { CORBA::ORB_var orb = CORBA::ORB_init(argc, argv); if( argc != 2 ) { cerr << "usage: eg2_clt <object reference>" << endl; return 1; } CORBA::Object_var obj = orb->string_to_object(argv[1]); Echo_var echoref = Echo::_narrow(obj); if( CORBA::is_nil(echoref) ) { cerr << "Can't narrow reference to type Echo (or it was nil)." << endl; return 1; } for (CORBA::ULong count=0; count<10; count++) hello(echoref); orb->destroy(); } catch(CORBA::TRANSIENT&) { cerr << "Caught system exception TRANSIENT -- unable to contact the " << "server." << endl; } catch(CORBA::SystemException& ex) { cerr << "Caught a CORBA::" << ex._name() << endl; } catch(CORBA::Exception& ex) { cerr << "Caught CORBA::Exception: " << ex._name() << endl; } catch(omniORB::fatalException& fe) { cerr << "Caught omniORB::fatalException:" << endl; cerr << " file: " << fe.file() << endl; cerr << " line: " << fe.line() << endl; cerr << " mesg: " << fe.errmsg() << endl; } return 0; }

2.12.4  eg3_impl.cc

// eg3_impl.cc - This is the source code of example 3 used in Chapter 2 // "The Basics" of the omniORB user guide. // // This is the object implementation. // // Usage: eg3_impl // // On startup, the object reference is registered with the // COS naming service. The client uses the naming service to // locate this object. // // The name which the object is bound to is as follows: // root [context] // | // test [context] kind [my_context] // | // Echo [object] kind [Object] // #include <echo.hh> #ifdef HAVE_STD # include <iostream> using namespace std; #else # include <iostream.h> #endif static CORBA::Boolean bindObjectToName(CORBA::ORB_ptr, CORBA::Object_ptr); class Echo_i : public POA_Echo { public: inline Echo_i() {} virtual ~Echo_i() {} virtual char* echoString(const char* mesg); }; char* Echo_i::echoString(const char* mesg) { return CORBA::string_dup(mesg); } ////////////////////////////////////////////////////////////////////// int main(int argc, char **argv) { try { CORBA::ORB_var orb = CORBA::ORB_init(argc, argv); CORBA::Object_var obj = orb->resolve_initial_references("RootPOA"); PortableServer::POA_var poa = PortableServer::POA::_narrow(obj); Echo_i* myecho = new Echo_i(); PortableServer::ObjectId_var myechoid = poa->activate_object(myecho); // Obtain a reference to the object, and register it in // the naming service. obj = myecho->_this(); CORBA::String_var x; x = orb->object_to_string(obj); cout << x << endl; if( !bindObjectToName(orb, obj) ) return 1; myecho->_remove_ref(); PortableServer::POAManager_var pman = poa->the_POAManager(); pman->activate(); orb->run(); } catch(CORBA::SystemException& ex) { cerr << "Caught CORBA::" << ex._name() << endl; } catch(CORBA::Exception& ex) { cerr << "Caught CORBA::Exception: " << ex._name() << endl; } catch(omniORB::fatalException& fe) { cerr << "Caught omniORB::fatalException:" << endl; cerr << " file: " << fe.file() << endl; cerr << " line: " << fe.line() << endl; cerr << " mesg: " << fe.errmsg() << endl; } return 0; } ////////////////////////////////////////////////////////////////////// static CORBA::Boolean bindObjectToName(CORBA::ORB_ptr orb, CORBA::Object_ptr objref) { CosNaming::NamingContext_var rootContext; try { // Obtain a reference to the root context of the Name service: CORBA::Object_var obj; obj = orb->resolve_initial_references("NameService"); // Narrow the reference returned. rootContext = CosNaming::NamingContext::_narrow(obj); if( CORBA::is_nil(rootContext) ) { cerr << "Failed to narrow the root naming context." << endl; return 0; } } catch (CORBA::NO_RESOURCES&) { cerr << "Caught NO_RESOURCES exception. You must configure omniORB " << "with the location" << endl << "of the naming service." << endl; return 0; } catch (CORBA::ORB::InvalidName&) { // This should not happen! cerr << "Service required is invalid [does not exist]." << endl; return 0; } try { // Bind a context called "test" to the root context: CosNaming::Name contextName; contextName.length(1); contextName[0].id = (const char*) "test"; // string copied contextName[0].kind = (const char*) "my_context"; // string copied // Note on kind: The kind field is used to indicate the type // of the object. This is to avoid conventions such as that used // by files (name.type -- e.g. test.ps = postscript etc.) CosNaming::NamingContext_var testContext; try { // Bind the context to root. testContext = rootContext->bind_new_context(contextName); } catch(CosNaming::NamingContext::AlreadyBound& ex) { // If the context already exists, this exception will be raised. // In this case, just resolve the name and assign testContext // to the object returned: CORBA::Object_var obj; obj = rootContext->resolve(contextName); testContext = CosNaming::NamingContext::_narrow(obj); if( CORBA::is_nil(testContext) ) { cerr << "Failed to narrow naming context." << endl; return 0; } } // Bind objref with name Echo to the testContext: CosNaming::Name objectName; objectName.length(1); objectName[0].id = (const char*) "Echo"; // string copied objectName[0].kind = (const char*) "Object"; // string copied try { testContext->bind(objectName, objref); } catch(CosNaming::NamingContext::AlreadyBound& ex) { testContext->rebind(objectName, objref); } // Note: Using rebind() will overwrite any Object previously bound // to /test/Echo with obj. // Alternatively, bind() can be used, which will raise a // CosNaming::NamingContext::AlreadyBound exception if the name // supplied is already bound to an object. // Amendment: When using OrbixNames, it is necessary to first try bind // and then rebind, as rebind on it's own will throw a NotFoundexception if // the Name has not already been bound. [This is incorrect behaviour - // it should just bind]. } catch(CORBA::TRANSIENT& ex) { cerr << "Caught system exception TRANSIENT -- unable to contact the " << "naming service." << endl << "Make sure the naming server is running and that omniORB is " << "configured correctly." << endl; return 0; } catch(CORBA::SystemException& ex) { cerr << "Caught a CORBA::" << ex._name() << " while using the naming service." << endl; return 0; } return 1; }

2.12.5  eg3_clt.cc

// eg3_clt.cc - This is the source code of example 3 used in Chapter 2 // "The Basics" of the omniORB user guide. // // This is the client. It uses the COSS naming service // to obtain the object reference. // // Usage: eg3_clt // // // On startup, the client lookup the object reference from the // COS naming service. // // The name which the object is bound to is as follows: // root [context] // | // text [context] kind [my_context] // | // Echo [object] kind [Object] // #include <echo.hh> #ifdef HAVE_STD # include <iostream> using namespace std; #else # include <iostream.h> #endif static CORBA::Object_ptr getObjectReference(CORBA::ORB_ptr orb); static void hello(Echo_ptr e) { if( CORBA::is_nil(e) ) { cerr << "hello: The object reference is nil!\n" << endl; return; } CORBA::String_var src = (const char*) "Hello!"; CORBA::String_var dest = e->echoString(src); cerr << "I said, \"" << (char*)src << "\"." << endl << "The Echo object replied, \"" << (char*)dest <<"\"." << endl; } ////////////////////////////////////////////////////////////////////// int main (int argc, char **argv) { try { CORBA::ORB_var orb = CORBA::ORB_init(argc, argv); CORBA::Object_var obj = getObjectReference(orb); Echo_var echoref = Echo::_narrow(obj); for (CORBA::ULong count=0; count < 10; count++) hello(echoref); orb->destroy(); } catch(CORBA::TRANSIENT&) { cerr << "Caught system exception TRANSIENT -- unable to contact the " << "server." << endl; } catch(CORBA::SystemException& ex) { cerr << "Caught a CORBA::" << ex._name() << endl; } catch(CORBA::Exception& ex) { cerr << "Caught CORBA::Exception: " << ex._name() << endl; } catch(omniORB::fatalException& fe) { cerr << "Caught omniORB::fatalException:" << endl; cerr << " file: " << fe.file() << endl; cerr << " line: " << fe.line() << endl; cerr << " mesg: " << fe.errmsg() << endl; } return 0; } ////////////////////////////////////////////////////////////////////// static CORBA::Object_ptr getObjectReference(CORBA::ORB_ptr orb) { CosNaming::NamingContext_var rootContext; try { // Obtain a reference to the root context of the Name service: CORBA::Object_var obj; obj = orb->resolve_initial_references("NameService"); // Narrow the reference returned. rootContext = CosNaming::NamingContext::_narrow(obj); if( CORBA::is_nil(rootContext) ) { cerr << "Failed to narrow the root naming context." << endl; return CORBA::Object::_nil(); } } catch (CORBA::NO_RESOURCES&) { cerr << "Caught NO_RESOURCES exception. You must configure omniORB " << "with the location" << endl << "of the naming service." << endl; return 0; } catch(CORBA::ORB::InvalidName& ex) { // This should not happen! cerr << "Service required is invalid [does not exist]." << endl; return CORBA::Object::_nil(); } // Create a name object, containing the name test/context: CosNaming::Name name; name.length(2); name[0].id = (const char*) "test"; // string copied name[0].kind = (const char*) "my_context"; // string copied name[1].id = (const char*) "Echo"; name[1].kind = (const char*) "Object"; // Note on kind: The kind field is used to indicate the type // of the object. This is to avoid conventions such as that used // by files (name.type -- e.g. test.ps = postscript etc.) try { // Resolve the name to an object reference. return rootContext->resolve(name); } catch(CosNaming::NamingContext::NotFound& ex) { // This exception is thrown if any of the components of the // path [contexts or the object] aren't found: cerr << "Context not found." << endl; } catch(CORBA::TRANSIENT& ex) { cerr << "Caught system exception TRANSIENT -- unable to contact the " << "naming service." << endl << "Make sure the naming server is running and that omniORB is " << "configured correctly." << endl; } catch(CORBA::SystemException& ex) { cerr << "Caught a CORBA::" << ex._name() << " while using the naming service." << endl; return 0; } return CORBA::Object::_nil(); }

2.12.6  eg3_tieimpl.cc

// eg3_tieimpl.cc - This example is similar to eg3_impl.cc except that // the tie implementation skeleton is used. // // This is the object implementation. // // Usage: eg3_tieimpl // // On startup, the object reference is registered with the // COS naming service. The client uses the naming service to // locate this object. // // The name which the object is bound to is as follows: // root [context] // | // test [context] kind [my_context] // | // Echo [object] kind [Object] // #include <echo.hh> #ifdef HAVE_STD # include <iostream> using namespace std; #else # include <iostream.h> #endif static CORBA::Boolean bindObjectToName(CORBA::ORB_ptr,CORBA::Object_ptr); // This is the object implementation. Notice that it does not inherit // from any stub class, and notice that the echoString() member // function does not have to be virtual. class Echo_i { public: inline Echo_i() {} inline ~Echo_i() {} char* echoString(const char* mesg); }; char* Echo_i::echoString(const char* mesg) { return CORBA::string_dup(mesg); } ////////////////////////////////////////////////////////////////////// int main(int argc, char** argv) { try { CORBA::ORB_var orb = CORBA::ORB_init(argc, argv); CORBA::Object_var obj = orb->resolve_initial_references("RootPOA"); PortableServer::POA_var poa = PortableServer::POA::_narrow(obj); // Note that the <myecho> tie object is constructed on the stack // here. It will delete its implementation (myimpl) when it it // itself destroyed (when it goes out of scope). It is essential // however to ensure that such servants are not deleted whilst // still activated. // // Tie objects can of course be allocated on the heap using new, // in which case they are deleted when their reference count // becomes zero, as with any other servant object. Echo_i* myimpl = new Echo_i(); POA_Echo_tie<Echo_i> myecho(myimpl); PortableServer::ObjectId_var myechoid = poa->activate_object(&myecho); // Obtain a reference to the object, and register it in // the naming service. obj = myecho._this(); if( !bindObjectToName(orb, obj) ) return 1; PortableServer::POAManager_var pman = poa->the_POAManager(); pman->activate(); orb->run(); } catch(CORBA::SystemException& ex) { cerr << "Caught CORBA::" << ex._name() << endl; } catch(CORBA::Exception& ex) { cerr << "Caught CORBA::Exception: " << ex._name() << endl; } catch(omniORB::fatalException& fe) { cerr << "Caught omniORB::fatalException:" << endl; cerr << " file: " << fe.file() << endl; cerr << " line: " << fe.line() << endl; cerr << " mesg: " << fe.errmsg() << endl; } return 0; } ////////////////////////////////////////////////////////////////////// static CORBA::Boolean bindObjectToName(CORBA::ORB_ptr orb, CORBA::Object_ptr objref) { CosNaming::NamingContext_var rootContext; try { // Obtain a reference to the root context of the Name service: CORBA::Object_var obj; obj = orb->resolve_initial_references("NameService"); // Narrow the reference returned. rootContext = CosNaming::NamingContext::_narrow(obj); if( CORBA::is_nil(rootContext) ) { cerr << "Failed to narrow the root naming context." << endl; return 0; } } catch (CORBA::NO_RESOURCES&) { cerr << "Caught NO_RESOURCES exception. You must configure omniORB " << "with the location" << endl << "of the naming service." << endl; return 0; } catch (CORBA::ORB::InvalidName&) { // This should not happen! cerr << "Service required is invalid [does not exist]." << endl; return 0; } try { // Bind a context called "test" to the root context: CosNaming::Name contextName; contextName.length(1); contextName[0].id = (const char*) "test"; // string copied contextName[0].kind = (const char*) "my_context"; // string copied // Note on kind: The kind field is used to indicate the type // of the object. This is to avoid conventions such as that used // by files (name.type -- e.g. test.ps = postscript etc.) CosNaming::NamingContext_var testContext; try { // Bind the context to root. testContext = rootContext->bind_new_context(contextName); } catch(CosNaming::NamingContext::AlreadyBound& ex) { // If the context already exists, this exception will be raised. // In this case, just resolve the name and assign testContext // to the object returned: CORBA::Object_var obj; obj = rootContext->resolve(contextName); testContext = CosNaming::NamingContext::_narrow(obj); if( CORBA::is_nil(testContext) ) { cerr << "Failed to narrow naming context." << endl; return 0; } } // Bind objref with name Echo to the testContext: CosNaming::Name objectName; objectName.length(1); objectName[0].id = (const char*) "Echo"; // string copied objectName[0].kind = (const char*) "Object"; // string copied try { testContext->bind(objectName, objref); } catch(CosNaming::NamingContext::AlreadyBound& ex) { testContext->rebind(objectName, objref); } // Note: Using rebind() will overwrite any Object previously bound // to /test/Echo with obj. // Alternatively, bind() can be used, which will raise a // CosNaming::NamingContext::AlreadyBound exception if the name // supplied is already bound to an object. // Amendment: When using OrbixNames, it is necessary to first try bind // and then rebind, as rebind on it's own will throw a NotFoundexception if // the Name has not already been bound. [This is incorrect behaviour - // it should just bind]. } catch(CORBA::TRANSIENT& ex) { cerr << "Caught system exception TRANSIENT -- unable to contact the " << "naming service." << endl << "Make sure the naming server is running and that omniORB is " << "configured correctly." << endl; return 0; } catch(CORBA::SystemException& ex) { cerr << "Caught a CORBA::" << ex._name() << " while using the naming service." << endl; return 0; } return 1; }

1
The stub code is the C++ code that provides the object mapping as defined in the CORBA specification.
2
In omniORB, all object reference variable types are instantiated from the template type _CORBA_ObjRef_Var.
3
However, the implementation of the type conversion operator between Echo_var and Echo_ptr varies slightly among different C++ compilers; you may need to do an explicit cast if the compiler complains about the conversion being ambiguous.
4
In the previous 1.0 version of the C++ mapping, servant reference counting was optional, chosen by inheriting from a mixin class named RefCountServantBase. That has been deprecated in the 1.1 version of the C++ mapping, but the class is still available as an empty struct, so existing code that inherits from RefCountServantBase will continue to work.
5
A conversion operator of CORBA::String_var converts a CORBA::String_var to a char*.
6
Please refer to the C++ mapping specification for details of the String_var mapping.
7
For backwards compatibility, the ORB identifiers ‘omniORB2’ and ‘omniORB3’ are also accepted.
8
If a system exception is not caught, the C++ runtime will call the terminate() function. This function is defaulted to abort the whole process and on some systems will cause a core file to be produced.
9
Run Time Type Identification
10
The POA itself can be activated on demand with an adapter activator.
11
There are escaping rules to cope with id and kind fields which contain ‘.’ and ‘/’ characters. See chapter 6 of this manual, and chapter 3 of the CORBA services specification, as updated for the Interoperable Naming Service [OMG00].

Previous Up Next