# Chapter 11 Type Any and TypeCode

The CORBA specification provides for a type that can hold the value of any OMG IDL type. This type is known as type Any. The OMG also specifies a pseudo-object, TypeCode, that can encode a description of any type specifiable in OMG IDL.
In this chapter, an example demonstrating the use of type Any is presented. This is followed by sections describing the behaviour of type Any and TypeCode in omniORB. For further information on type Any, refer to the C++ Mapping specification., and for more information on TypeCode, refer to the Interface Repository chapter in the CORBA core section of the CORBA specification.

  Warning
  Since 2.8.0, omniORB has been updated to CORBA 2.3 and above. In order to comply with the 2.3 specification, it was necessary to change the semantics of the extraction of string, object reference and typecode from an Any. The memory of the extracted values of these types now belongs to the Any value. The storage is freed when the Any value is deallocated. Previously the extracted value was a copy and the application was responsible for releasing the storage. It is not possible to detect the old usage at compile time. In particular, unmodified code that uses the affected Any extraction operators will most certainly cause runtime errors to occur. To smooth the transition from the old usage to the new, an ORB configuration parameter `omniORB_27_CompatibleAnyExtraction` can be set to revert the Any extraction operators to the old semantics.

## 11.1 Example using type Any

Before going through this example, you should make sure that you have read and understood the examples in chapter 25The Basicschapter.2. The source code for this example is included in the omniORB distribution, in the directory `src/examples/anyExample`. A listing of the source code is provided at the end of this chapter.

### 11.1.1 Type Any in IDL

Type Any allows one to delay the decision on the type used in an operation until run-time. To use type any in IDL, use the keyword `any`, as in the following example:

    // IDL

    interface anyExample {
      any testOp(in any mesg);
    };

The operation `testOp()()` in this example can now take any value expressible in OMG IDL as an argument, and can also return any type expressible in OMG IDL.
Type Any is mapped into C++ as the type `CORBA::Any`. When passed as an argument or as a result of an operation, the following rules apply:

In | InOut | Out | Return

`const CORBA::Any&` | `CORBA::Any&` | `CORBA::Any*&` | `CORBA::Any*`

So, the above IDL would map to the following C++:

    // C++

    class anyExample_i : public virtual POA_anyExample {
    public:
      anyExample_i() { }
      virtual ~anyExample_i() { }
      virtual CORBA::Any* testOp(const CORBA::Any& a);
    };

### 11.1.2 Inserting and Extracting Basic Types from an Any

The question now arises as to how values are inserted into and removed from an Any. This is achieved using two overloaded operators: `<<=` and `>>=`.
To insert a value into an Any, the `<<=` operator is used, as in this example:

    // C++
    CORBA::Any an_any;
    CORBA::Long l = 100;
    an_any <<= l;

Note that the overloaded `<<=` operator has a return type of `void`.
To extract a value, the `>>=` operator is used, as in this example (where the Any contains a long):

    // C++
    CORBA::Long l;
    an_any >>= l;

    cout << "This is a long: " << l << endl;

The overloaded `>>=` operator returns a `CORBA::Boolean`. If an attempt is made to extract a value from an Any when it contains a different type of value (e.g. an attempt to extract a long from an Any containing a double), the overloaded `>>=` operator will return False; otherwise it will return True. Thus, a common tactic to extract values from an Any is as follows:

    // C++
    CORBA::Long l;
    CORBA::Double d;
    const char* str;     // From CORBA 2.3 onwards, uses const char*
                         // instead of char*.

    if (an_any >>= l) {
        cout << "Long: " << l << endl;
    }
    else if (an_any >>= d) {
        cout << "Double: " << d << endl;
    }
    else if (an_any >>= str) {
        cout << "String: " << str << endl;
        // Since 2.8.0 the storage of the extracted string is still
        // owned by the any.
        // In pre-omniORB 2.8.0 releases, the string returned is a copy.
    }
    else {
        cout << "Unknown value." << endl;
    }

### 11.1.3 Inserting and Extracting Constructed Types from an Any

It is also possible to insert and extract constructed types and object references from an Any. omniidl will generate insertion and extraction operators for the constructed type. Note that it is necessary to specify the `-WBa` command-line flag when running omniidl in order to generate these operators. The following example illustrates the use of constructed types with type Any:

    // IDL
    struct testStruct {
      long l;
      short s;
    };

    interface anyExample {
      any testOp(in any mesg);
    };

Upon compiling the above IDL with `omniidl -bcxx -Wba`, the following overloaded operators are generated:

1. `void operator<<=(CORBA::Any&, const testStruct&)`
2. `void operator<<=(CORBA::Any&, testStruct*)`
3. `CORBA::Boolean operator>>=(const CORBA::Any&,`
   `const testStruct*&)`

Operators of this form are generated for all constructed types, and for interfaces.
The first operator, (1), copies the constructed type, and inserts it into the Any. The second operator, (2), inserts the constructed type into the Any, and then manages it. Note that if the second operator is used, the Any consumes the constructed type, and the caller should not use the pointer to access the data after insertion. The following is an example of how to insert a value into an Any using operator (1):

    // C++
    CORBA::Any an_any;

    testStruct t;
    t.l = 456;
    t.s = 8;

    an_any <<= t;

The third operator, (3), is used to extract the constructed type from the Any, and can be used as follows:

    const testStruct* tp;   // From CORBA 2.3 onwards, use
                            // const testStruct* instead of testStruct*

    if (an_any >>= tp) {
        cout << "testStruct: l: " << tp->l << endl;
        cout << "            s: " << tp->s << endl;
    }
    else {
        cout << "Unknown value contained in Any." << endl;
    }

As with basic types, if an attempt is made to extract a type from an Any that does not contain a value of that type, the extraction operator returns False. If the Any does contain that type, the extraction operator returns True. If the extraction is successful, the caller's pointer will point to memory managed by the Any. The caller must not delete or otherwise change this storage, and should not use this storage after the contents of the Any are replaced (either by insertion or assignment), or after the Any has been destroyed. In particular, management of the pointer should not be assigned to a `_var` type.
If the extraction fails, the caller's pointer will be set to point to null.
Note that there are special rules for inserting and extracting arrays (using the `_forany` types), and for inserting and extracting bounded strings, booleans, chars, and octets. Please refer to the C++ Mapping specification for further information.

## 11.2 Type Any in omniORB

This section contains some notes on the use and behaviour of type Any in omniORB.

##### Generating Insertion and Extraction Operators.

To generate type Any insertion and extraction operators for constructed types and interfaces, the `-Wba` command line flag should be specified when running omniidl.

##### TypeCode comparison when extracting from an Any.

When an attempt is made to extract a type from an Any, the TypeCode of the type is checked for equivalence with the TypeCode of the type stored by the Any. The `equivalent()` test in the TypeCode interface is used for this purpose1.
Examples:

    // IDL 1
    typedef double Double1;

    struct Test1 {
      Double1 a;
    };

    // IDL 2
    typedef double Double2;

    struct Test1 {
      Double2 a;
    };

If an attempt is made to extract the type `Test1` defined in IDL 1 from an Any containing the `Test1` defined in IDL 2, this will succeed (and vice-versa), as the two types differ only by an alias.

##### Top-level aliases.

When a type is inserted into an Any, the Any stores both the value of the type and the TypeCode for that type. The treatment of top-level aliases from omniORB 2.8.0 onwards is different from pre-omniORB 2.8.0 releases.
In pre-omniORB 2.8.0 releases, if there are any top-level `tk_alias` TypeCodes in the TypeCode, they will be removed from the TypeCode stored in the Any. Note that this does not affect the `_tc_` TypeCode generated to represent the type (see section on TypeCode, below). This behaviour is necessary, as two types that differ only by a top-level alias can use the same insertion and extraction operators. If the `tk_alias` is not removed, one of the types could be transmitted with an incorrect `tk_alias` TypeCode. Example:

    // IDL 3
    typedef sequence<double> seqDouble1;
    typedef sequence<double> seqDouble2;
    typedef seqDouble2       seqDouble3;

If either `seqDouble1` or `seqDouble2` is inserted into an Any, the TypeCode stored in the Any will be for a `sequence<double>`, and not for an alias to a `sequence<double>`.
From omniORB 2.8.0 onwards, there are two changes. Firstly, in the example, `seqDouble1` and `seqDouble2` are now distinct types and therefore each has its own set of C++ operators for Any insertion and extraction. Secondly, the top level aliases are not removed. For example, if `seqDouble3` is inserted into an Any, the insertion operator for `seqDouble2` is invoked (because `seqDouble3` is just a C++ typedef of `seqDouble2`). Therefore, the TypeCode in the Any would be that of seqDouble2. If this is not desirable, one can use the new member function ``void type(TypeCode_ptr)`' of the Any interface to explicitly set the TypeCode to the correct one.

##### Removing aliases from TypeCodes.

Some ORBs (such as Orbix) will not accept TypeCodes containing `tk_alias` TypeCodes. When using type Any while interoperating with these ORBs, it is necessary to remove `tk_alias` TypeCodes from throughout the TypeCode representing a constructed type.
To remove all `tk_alias` TypeCodes from TypeCodes stored in Anys, supply the `-ORBtcAliasExpand 1` command-line flag when running an omniORB executable. There will be some (small) performance penalty when inserting values into an Any.
Note that the `_tc_` TypeCodes generated for all constructed types will contain the complete TypeCode for the type (including any `tk_alias` TypeCodes), regardless of whether the `-ORBtcAliasExpand` flag is set to 1 or not.

##### Recursive TypeCodes.

omniORB (as of version 2.7) supports recursive TypeCodes. This means that types such as the following can be inserted or extracted from an Any:

    // IDL 4
    struct Test4 {
      sequence<Test4> a;
    };

##### Threads and type Any.

Inserting and extracting simultaneously from the same Any (in 2 different threads) is undefined behaviour.
Extracting simultaneously from the same Any (in 2 or more different threads) also leads to undefined behaviour. It was decided not to protect the Any with a mutex, as this condition should rarely arise, and adding a mutex would lead to performance penalties.

## 11.3 TypeCode in omniORB

This section contains some notes on the use and behaviour of TypeCode in omniORB

##### TypeCodes in IDL.

When using TypeCodes in IDL, note that they are defined in the CORBA scope. Therefore, `CORBA::TypeCode` should be used. Example:

    // IDL 5
    struct Test5 {
      long length;
      CORBA::TypeCode desc;
    };

##### orb.idl

Inclusion of the file `orb.idl` in IDL using `CORBA::TypeCode` is optional. An empty `orb.idl` file is provided for compatibility purposes.

##### Generating TypeCodes for constructed types.

To generate a TypeCode for constructed types, specify the `-Wba` command-line flag when running omniidl. This will generate a `_tc_` TypeCode describing the type, at the same scope as the type (as per the CORBA 2.3 specification). Example:

    // IDL 6
    struct Test6 {
      double a;
      sequence<long> b;
    };

A TypeCode, `_tc_Test6`, will be generated to describe the struct `Test6`. The operations defined in the TypeCode interface can be used to query the TypeCode about the type it represents.

##### TypeCode equality.

The behaviour of `CORBA::TypeCode::equal()` member function from omniORB 2.8.0 onwards is different from pre-omniORB 2.8.0 releases. In summary, the pre-omniORB 2.8.0 is close to the semantics of the new `CORBA::TypeCode::equivalent()` member function. Details are as follows:
The `CORBA::TypeCode::equal()` member function will now return true only if the two TypeCodes are exactly the same. `tk_alias` TypeCodes are included in this comparison, unlike the comparison made when values are extracted from an Any (see section on Any, above).
In pre-omniORB 2.8.0 releases, equality test would ignore the optional fields when one of the fields in the two typecodes is empty. For example, if one of the TypeCodes being checked is a `tk_struct`, `tk_union`, `tk_enum`, or `tk_alias`, and has an empty repository ID parameter, then the repository ID parameter will be ignored when checking for equality. Similarly, if the `name` or `member_name` parameters of a TypeCode are empty strings, they will be ignored for equality checking purposes. This is because a CORBA 2 ORB does not have to include these parameters in a TypeCode (see the Interoperability section of the CORBA specification). Note that these (optional) parameters are included in TypeCodes generated by omniORB.
Since CORBA 2.3, the issue of TypeCode equality has been clarified. There is now a new member `CORBA::TypeCode::equivalent()` which provides the semantics of the `CORBA::TypeCode::equal()` as implemented in omniORB releases prior to 2.8.0. So from omniORB 2.8.0 onwards, the `CORBA::TypeCode::equal()` function has been changed to enforce strict equality. The pre-2.8.0 behaviour can be obtained with `equivalent()`.

## 11.4 Source Listing

### 11.4.1 anyExample_impl.cc

    // anyExample_impl.cc - This is the source code of the example used in
    //                      Chapter 9 "Type Any and TypeCode" of the omniORB
    //                      users guide.
    //
    //                      This is the object implementation.
    //
    // Usage: anyExample_impl
    //
    //        On startup, the object reference is printed to cerr as a
    //        stringified IOR. This string should be used as the argument to
    //        anyExample_clt.
    //

    #include <iostream.h>
    #include <anyExample.hh>

    class anyExample_i : public POA_anyExample {
    public:
      inline anyExample_i() {}
      virtual ~anyExample_i() {}
      virtual CORBA::Any* testOp(const CORBA::Any& a);
    };

    CORBA::Any* anyExample_i::testOp(const CORBA::Any& a)
    {
      cout << "Any received, containing: " << endl;

    #ifndef NO_FLOAT
      CORBA::Double d;
    #endif

      CORBA::Long l;
      const char* str;

      testStruct* tp;

      if (a >>= l) {
        cout << "Long: " << l << endl;
      }
    #ifndef NO_FLOAT
      else if (a >>= d) {
        cout << "Double: " << d << endl;
      }
    #endif
      else if (a >>= str) {
        cout << "String: " << str << endl;
      }
      else if (a >>= tp) {
        cout << "testStruct: l: " << tp->l << endl;
        cout << "            s: " << tp->s << endl;
      }
      else {
        cout << "Unknown value." << endl;
      }

      CORBA::Any* ap = new CORBA::Any;

      *ap <<= (CORBA::ULong) 314;

      cout << "Returning Any containing: ULong: 314\n" << endl;
      return ap;
    }

    //////////////////////////////////////////////////////////////////////

    int main(int argc, char** argv)
    {
      try {
        CORBA::ORB_var orb = CORBA::ORB_init(argc, argv, "omniORB3");

        CORBA::Object_var obj = orb->resolve_initial_references("RootPOA");
        PortableServer::POA_var poa = PortableServer::POA::_narrow(obj);

        anyExample_i* myobj = new anyExample_i();

        PortableServer::ObjectId_var myobjid = poa->activate_object(myobj);

        obj = myobj->_this();
        CORBA::String_var sior(orb->object_to_string(obj));
        cerr << "'" << (char*)sior << "'" << endl;

        myobj->_remove_ref();

        PortableServer::POAManager_var pman = poa->the_POAManager();
        pman->activate();

        orb->run();
        orb->destroy();
      }
      catch(CORBA::SystemException&) {
        cerr << "Caught CORBA::SystemException." << endl;
      }
      catch(CORBA::Exception&) {
        cerr << "Caught CORBA::Exception." << 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;
      }
      catch(...) {
        cerr << "Caught unknown exception." << endl;
      }
      return 0;
    }

### 11.4.2 anyExample_clt.cc

    // anyExample_clt.cc -  This is the source code of the example used in
    //                      Chapter 9 "Type Any and TypeCode" of the omniORB
    //                      users guide.
    //
    //                      This is the client.
    //
    // Usage: anyExample_clt <object reference>
    //

    #include <iostream.h>
    #include <anyExample.hh>

    static void invokeOp(anyExample_ptr& tobj, const CORBA::Any& a)
    {
      CORBA::Any_var bp;

      cout << "Invoking operation." << endl;
      bp = tobj->testOp(a);

      cout << "Operation completed. Returned Any: ";
      CORBA::ULong ul;

      if (bp >>= ul) {
        cout << "ULong: " << ul << "\n" << endl;
      }
      else {
        cout << "Unknown value." << "\n" << endl;
      }
    }

    static void hello(anyExample_ptr tobj)
    {
      CORBA::Any a;

      // Sending Long
      CORBA::Long l = 100;
      a <<= l;
      cout << "Sending Any containing Long: " << l << endl;
      invokeOp(tobj,a);

      // Sending Double
    #ifndef NO_FLOAT
      CORBA::Double d = 1.2345;
      a <<= d;
      cout << "Sending Any containing Double: " << d << endl;
      invokeOp(tobj,a);
    #endif

      // Sending String
      const char* str = "Hello";
      a <<= str;
      cout << "Sending Any containing String: " << str << endl;
      invokeOp(tobj,a);

      // Sending testStruct  [Struct defined in IDL]
      testStruct t;
      t.l = 456;
      t.s = 8;
      a <<= t;
      cout << "Sending Any containing testStruct: l: " << t.l << endl;
      cout << "                                   s: " << t.s << endl;
      invokeOp(tobj,a);
    }

    //////////////////////////////////////////////////////////////////////

    int main(int argc, char** argv)
    {
      try {
        CORBA::ORB_var orb = CORBA::ORB_init(argc, argv, "omniORB3");

        if( argc != 2 ) {
          cerr << "usage:  anyExample_clt <object reference>" << endl;
          return 1;
        }

        CORBA::Object_var obj = orb->string_to_object(argv[1]);
        anyExample_var ref = anyExample::_narrow(obj);
        if( CORBA::is_nil(ref) ) {
          cerr << "Can't narrow reference to type anyExample (or it was nil)."
        << endl;
          return 1;
        }
        hello(ref);

        orb->destroy();
      }
      catch(CORBA::COMM_FAILURE& ex) {
        cerr << "Caught system exception COMM_FAILURE -- unable to contact the "
             << "object." << endl;
      }
      catch(CORBA::SystemException&) {
        cerr << "Caught a CORBA::SystemException." << endl;
      }
      catch(CORBA::Exception&) {
        cerr << "Caught CORBA::Exception." << 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;
      }
      catch(...) {
        cerr << "Caught unknown exception." << endl;
      }
      return 0;
    }

1
  In pre-omniORB 2.8.0 releases, omniORB performs an equality test and will ignore any alias TypeCodes (`tk_alias`) when making this comparison. The semantics is similar to the `equivalent()` test in the TypeCode interface of CORBA 2.3.