Extract data from a PubSubBuffer
- Last UpdatedApr 08, 2026
- 2 minute read
This scenario guides you through the steps required to extract the following values from a PubSubBuffer:
- Enumeration
- String
- Boolean
- Int32
- PubSubBuffer
To identify the code associated with each step, see the code comments in the Example code sections.
The values detailed in the procedure must be extracted in the same order that they were written. For more information, see Write data into a PubSubBuffer.
To extract from a PubSubBuffer
- Open the Program.cs file from the created project.
- Initialize a PubSubBuffer.
- Copy the byte array into the created PubSubBuffer.
- Read each value in the same order that they were written.
- Read the enumeration value as a System.Byte, and then cast it to the enumeration type.
- Create a new PubSubBuffer to read the latest item written.
- Read the PubSubBuffer.
- Dispose the buffer used to extract all the data and the Marshal pointer.
Example code
public void ExtractFromBuffer(byte[] data)
{
// Initialize a PubSubBuffer.
var buffer = new PubSubBuffer();
var size = data.Length;
var ptr = Marshal.AllocHGlobal(size);
try
{
// Copy the byte array into the created PubSubBuffer.
Marshal.Copy(data, 0, ptr, data.Length);
buffer.SetBuffer(ptr, size, size);
buffer.RewindBuffer();
if (buffer.MoreItemsToRead() == true)
{
// Read each value in the same order than they were written.
// Read the enumeration value as a System.Byte, and then cast it to the enumeration type.
Byte msgType;
buffer.Read(out msgType);
var dalPSMsgType = (DALPSMessageType)msgType;
Console.WriteLine("DALPSMessageType: " + dalPSMsgType);
// Read String value
String topic;
buffer.Read(out topic);
Console.WriteLine("Topic: " + topic);
// Read Boolean value.
Boolean boolValue;
buffer.Read(out boolValue);
Console.WriteLine("PubSubHeaderData: " + boolValue);
// Read Int32 value.
Int32 psBufferLength;
buffer.Read(out psBufferLength);
Console.WriteLine("Internal buffer Length: " + psBufferLength);
// Create a new PubSubBuffer to read the latest item written.
var psBuffer = new PubSubBuffer();
if (psBufferLength != 0)
{
// Read the PubSubBuffer.
var bufferData = new byte[psBufferLength];
buffer.ReadBlob(out bufferData);
var ptrToInnerBuffer = Marshal.AllocHGlobal(psBufferLength);
Marshal.Copy(bufferData, 0, ptrToInnerBuffer, psBufferLength);
psBuffer.SetBuffer(ptrToInnerBuffer, psBufferLength, psBufferLength);
psBuffer.RewindBuffer();
}
}
else
{
Console.WriteLine("Buffer is not initialized.");
}
}
catch (Exception exception)
{
throw exception;
}
finally
{
// Dispose the buffer used to extract all the data and the Marshal pointer.
buffer.Dispose();
Marshal.FreeHGlobal(ptr);
}
}