The **PDU_Factory** is based on the [Factory Design Pattern](http://en.wikipedia.org/wiki/Factory_design_pattern) The **PDU_Factory** converts any DIS network packet into its correct PDU format and returns this PDU as a safe pointer to the PDU base class(_Header_). **Note:** An example of using the **PDU_Factory** can also be found in the examples folder that comes with the KDIS distribution.
We first need to include the relevant header file/s. We need to include the PDU_Factory.h which can be found in the _KDIS/Extras_ folder. #include "KDIS/Extras/PDU_Factory.h"
We first need to create a **PDU_Factory** object. PDU_Factory Factory;
In version **1-15-0** and onwards it is possible to add a filter to the PDU factory. // Lets apply a filter to the factory so it only lets through PDU that have an exercise ID of 1. Factory.AddFilter( new FactoryFilterExerciseID( 1 ) ); See [Creating_Custom_PDU_Factory_Filters] for further details on filters.
We are now ready to start decoding DIS data. **Note:** I do not cover the use of sockets in this tutorial but the PDU_Factory example does come with some simple sockets that will work in Windows only. The DIS network data should have been received in a char array format. in this example a KOCTET represents a char datatype. KOCTET cBuffer[MAX_PDU_SIZE]; // This is our buffer **Note:** MAX_PDU_SIZE is defined in KDefines.h, it is the maximun size a PDU can be in DIS. It should be safe to use this value for your buffer/s. Once some DIS data has been received into the buffer we can use the **PDU_Factory** to decode it. auto_ptr<Header> pHeader = Factory.Decode( cBuffer, ui32Recv ); // ui32Recv should be the size of the data packet received.
We now have a auto_ptr to the base class of our PDU. The auto_ptr is a safe pointer belonging to the STL. When the auto_ptr object goes out of scope it will delete the pointer contained within thus preventing memory leaks. We now have 2 options.
We could just let the object expire if we are not interested in it, we do not need to do anything, the auto_ptr will clean up memory when it goes out of scope.
E.G if we only wanted PDU that belonged to the Entity Info Interaction protocol family we could do the following:
if( pHeader->GetProtocolFamily() == Entity_Infomation_Interaction )
{
Entity_State_PDU * pES = dynamic_cast<Entity_State_PDU*>( pHeader.get() );
if( pES )
{
// Upcast was successful, now what?
}
This method is fine providing we don’t mind the PDU being deleted once we go out of scope, but what is we wanted to keep the PDU?
We can prevent the auto_ptr from deleting the PDU pointer when it goes out of scope by taking ownership of the pointer. We do this using the _release_ function.
E.G if we wanted the contents of a Entity_State_PDU:
Entity_State_PDU * pES = dynamic_cast<Entity_State_PDU*>( pHeader.release() );
if( pES )
{
// Upcast was successful and we now have complete ownership of it. Don’t forget to delete it when you are finished. delete pES;
}