Namespace Unity.Networking.Transport.LowLevel.Unsafe
Classes
DataStreamUnsafeUtility
DataStream (Reader/Writer) unsafe utilities used to do pointer operations on streams.
These are added to the DataStreamWriter
/DataStreamReader
classes as extensions, so
you need to add using Unity.Collections.LowLevel.Unsafe
at the top
of file where you need to access these functions.
Since these are unsafe C# operations care must be taken when using them, it can easily crash the editor/player.
Every time data is written directly to the data stream buffer you must call
WriteBytesWithUnsafePointer
afterwards with the length of the data written so
that the stream class can internally keep track of how much of the internal
buffer has been written to.
The functions have read/write access check variants which utilize the job system atomic safety handle. The ENABLE_UNITY_COLLECTIONS_CHECKS define needs to be used for this to work. For more information see Unity.Collections.LowLevel.Unsafe.AtomicSafetyHandle.
Example of typical usage:
// Manually write some numbers into a data stream from a source buffer.
var data = new DataStreamWriter(4, Allocator.Temp);
unsafe
{
var ptr = data.GetUnsafePtr();
var sourceData = new NativeArray<byte>(4, Allocator.Temp);
sourceData[0] = 42;
sourceData[1] = 42;
sourceData[2] = 42;
sourceData[3] = 42;
UnsafeUtility.MemCpy(ptr, sourceData.GetUnsafePtr(), sourceData.Length);
data.WriteBytesWithUnsafePointer(sourceData.Length);
}