MemCpy & in parameter type = crash ?

Hi !

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 :confused:

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.

1 Like

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.

1 Like

Make sense and a little sad to not push further speed optimization but it will be fine for now :slight_smile: Thanks both of you

Is it burst related? I reported a bug with in pointers a year ago (that was fixed)

If so I’d go report it on the burst forum.