I added a Insert range in front extension to DynamicBuffer because a native version doesn’t exist. ( Unity team please add a InsertRange to collections !)
It seems my code create raw crashes when the buffer to be added is transferred with in parameter type but works fine when I use ref parameter type.
During my tries, newData always come from a Entity.Foreach call with parameter type matching method one.
public static unsafe void InsertInFront<T>(this ref DynamicBuffer<T> target, ref DynamicBuffer<T> newData) where T : struct, IBufferElementData
{
target.ResizeUninitialized(target.Length + newData.Length);
byte* pointer = (byte*)target.GetUnsafePtr();
int elemSize = UnsafeUtility.SizeOf<T>();
int newDataTotalSize = newData.Length * elemSize;
UnsafeUtility.MemMove(pointer + newDataTotalSize, pointer, target.Length * (long)elemSize);
UnsafeUtility.MemCpy(pointer, newData.GetUnsafeReadOnlyPtr(), newDataTotalSize);
}
I know crash is caused by the MemCpy because remove it prevents crashes.
I don’t understand how in parameter type can provoke that
The main difference between in and ref is that C# makes a defensive copy of in parameters in lots of very surprising situations. I don’t totally follow how that would crash here but I would be surprised if that wasn’t the core issue.
If the target type is not a readonly struct, it is more likely that “in” will create a defensive copy. for normal structs depends on which fields are used and whether the fields are readonly. Since, to my knowledge, DynamicBuffer is not a readonly struct and has no readonly fields, a defensive copy will certainly be created.