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.
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.
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?
Thank you Gerardo for posting this C example! Out of curiousity, where would I find similar documentation/examples in the RTI documentation? Does it exist?
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.
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
_dvariable directly? As well as the members of the internal_ustructure?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;Thank you Gerardo for posting this C example! Out of curiousity, where would I find similar documentation/examples in the RTI documentation? Does it exist?
Thanks