kumar_m_kiran
kumar_m_kiran

Reputation: 4022

How to represent IDL with union and switch in C++

We publish the IDL files to represent the interface and would have a similar structure with C++/C code so that we can use to map them when the interface is invoked. So some conversion (equivalent) representation would be required.
Like a sequence in IDL is represented by list in C++ and etc.

Recently, I came across a complex (unique), valid IDL file like -

union HostAddress switch(EAddType)
 {  
      case E_IPV_4:  
          char ipv4Addr[4];  
      case E_IPV_6:  
           char ipv6Addr[16]; 
 };

Upvotes: 2

Views: 4158

Answers (3)

Brian Neal
Brian Neal

Reputation: 32399

An IDL union is similar to a union in C or C++. The fields share the same memory in order to save space. You can find the complete set of rules for how the IDL union maps to C++ in the IDL to C++ Mapping Document.

In general my advice would be to avoid them. They are confusing and difficult to use in the C++ mapping.

Upvotes: 0

kumar_m_kiran
kumar_m_kiran

Reputation: 4022

I did find a good explanation at Websphere documentation, CORBA documentation. I particularly liked the detailed explanation in CORBA documentation. Any additional input, please answer to my post!

So the below example

union HostAddress switch(EAddType)
 {  
      case E_IPV_4:  
          char ipv4Addr[4];  
      case E_IPV_6:  
           char ipv6Addr[16]; 
 };

would be implemented as -

struct HostAddress
{
    EIPVSET _discriminant;
    long _d() { return _discriminant; }

    HostAddress() { _discriminant = E_IPV_INVALID; }
    string addressIpv6()   //get function overloaded
    {
       return string(this.ipv6Addr);
    }

    void addressIpv6(const string& ipv6Addr) //set function overloaded
    {
        strncpy(this.ipv6Addr,ipv6Addr.c_str(),16);
        return;
    }

    //similarly for other member variables.

}

Upvotes: 0

h4ck3rm1k3
h4ck3rm1k3

Reputation: 2100

A union structure gives you an opaque data block that is large enough to contain the largest of the members. in this case you will have an object with the type field and then 16 bytes to contain the ipv6 address and it will also store the ipv4 address, this allows you to make simple code that can process both ipv4 and v6 addresses without the expense of a full object. Unions are normally used for small objects like this where you will waste space to have a unified object that can handle all the cases. see wikipedia article on Unions and wikibook page on Unions

hope that helps.

Upvotes: 0

Related Questions