Working with IDL types - Union

4 posts / 0 new
Last post
Offline
Last seen: 2 years 9 months ago
Joined: 09/12/2014
Posts: 6
Working with IDL types - Union

Possible to give an example of how to use Union in Modern C++. I don't see any nice example of how to initialize a union, its discriminator and its member.

 

 

Gerardo Pardo's picture
Offline
Last seen: 1 week 20 hours ago
Joined: 06/02/2010
Posts: 598

See the attached ZIP file. 

The UnionType_publisher.cxx shows  how to set the union in modern C++. You basically use the setter of the union branch you want. The discriminator is set automatically.

The UnionType_subscriber.cxx shows  how to access the union discriminator modern C++. There is an operation called "_d()" that returns it. Then you use the proper getter for the branch that corresponds to that value of the discriminator.

 

 

 

File Attachments: 
ilya_1725's picture
Offline
Last seen: 1 month 1 week ago
Joined: 04/20/2020
Posts: 21

Gerardo, do you have an example how to use unions with C or classical C++?

The modern C++ creates access methods for all members. C doesn't. As a result, is it required to se the  _d variable directly? As well as the members of the internal  _u structure?

 

Gerardo Pardo's picture
Offline
Last seen: 1 week 20 hours ago
Joined: 06/02/2010
Posts: 598

Hi,

Yes, for C and Traditional C++ you have to set the value of the "_d" member directly as well as the corresponding member in the nested "_u" structure.

For example, assume the IDL union below:

union MyUnion switch (long) {
    case 1:
      long long_branch;
    case 3:
      float float_branch;
    case 4:
      char  char_branch;
};

If you generate C code for this you will get the following type:

typedef struct MyUnion {

    DDS_Long _d;
    struct MyUnion_u 
    {

        DDS_Long   long_branch ;
        DDS_Float   float_branch ;
        DDS_Char   char_branch ;
    }_u;

} MyUnion ;

Then to set the float_branch (discriminator value 3) to some value (e.g. 23.4) in the C code you would use something like this

    // Assume instance is a pointer to  struct MyUnion 
    instance->_d = 3;
    instance->_u.float_branch = 22.5;