Using a Type-Specific DataWriter (FooDataWriter)

(Note: This section does not apply to the Modern C++ API, where a DataWriter's data type is part of its template definition: DataWriter<Foo>)

Recall that a Topic is bound to a data type that specifies the format of the data associated with the Topic. Data types are either defined dynamically or in code generated from definitions in IDL or XML; see Data Types and DDS Data Samples. For each of your application's generated data types, such as 'Foo', there will be a FooDataWriter class (or a set of functions in C). This class allows the application to use a type-safe interface to interact with DDS samples of type 'Foo'. You will use the FooDataWriter's write() operation used to send data. For dynamically defined data-types, you will use the DynamicDataWriter class.

In fact, you will use the FooDataWriter any time you need to perform type-specific operations, such as registering or writing instances. DataWriter Operations indicates which operations must be called using FooDataWriter. For operations that are not type-specific, you can call the operation using either a FooDataWriter or a DDSDataWriter object1In the C API, the non type-specific operations must be called using a DDS_DataWriter pointer..

You may notice that the Publisher’s create_datawriter() operation returns a pointer to an object of type DDSDataWriter; this is because the create_datawriter() method is used to create DataWriters of any data type. However, when executed, the function actually returns a specialization (an object of a derived class) of the DataWriter that is specific for the data type of the associated Topic. For a Topic of type ‘Foo’, the object actually returned by create_datawriter() is a FooDataWriter.

To safely cast a generic DDSDataWriter pointer to a FooDataWriter pointer, you should use the static narrow() method of the FooDataWriter class. The narrow() method will return NULL if the generic DDSDataWriter pointer is not pointing at an object that is really a FooDataWriter.

For instance, if you create a Topic bound to the type ‘Alarm’, all DataWriters created for that Topic will be of type ‘AlarmDataWriter.’ To access the type-specific methods of AlarmDataWriter, you must cast the generic DDSDataWriter pointer returned by create_datawriter(). For example:

DDSDataWriter* writer = publisher->create_datawriter(
    topic,writer_qos, NULL, NULL);
AlarmDataWriter *alarm_writer = AlarmDataWriter::narrow(writer); if (alarm_writer == NULL) { // ... error };

In the C API, there is also a way to do the opposite of narrow(). FooDataWriter_as_datawriter() casts a FooDataWriter as a DDSDataWriter, and FooDataReader_as_datareader() casts a FooDataReader as a DDSDataReader.

© 2018 RTI