Search Unity

Questions about UnsafeUtility.Malloc

Discussion in 'Entity Component System' started by fholm, Nov 20, 2018.

  1. fholm

    fholm

    Joined:
    Aug 20, 2011
    Posts:
    2,052
    Just a few questions around the UnsafeUtility.Malloc function, since there's no API docs available as far as I know.

    1) What are the valid values for the alignment (second) parameter?
    2) What does the 'alignment' parameter control? I know what memory alignment is and how it works, but specifically what does the 'alignment' parameter do? Is it which alignment the memory is allocated at? i.e. the alignment of the pointer returned? Does it also control the stride of the memory allocated?

    I've worked under the current assumption for now:

    1) Valid values for alignment is 4, 8 and 16.
    2) The alignment parameter controls the alignment of the pointer returned, but not the stride of the memory.

    Is this correct?
     
    chadfranklin47 likes this.
  2. tertle

    tertle

    Joined:
    Jan 25, 2011
    Posts:
    3,761
    The unsafe utility get alignment method is hard coded to return 4 regardless of type so I just stick with that.
     
  3. fholm

    fholm

    Joined:
    Aug 20, 2011
    Posts:
    2,052
    Yeah I've seen this also in the code of UnsafeUtility.AlignOf<T>, but when dealing with values such as int64 and doubles some platforms do not like reading those on a non-8byte boundry.
     
  4. fholm

    fholm

    Joined:
    Aug 20, 2011
    Posts:
    2,052
    For example, if I'm going to allocate a buffer of uint64 like this:

    Code (csharp):
    1.  
    2.       var bufferSize = 256;
    3.       var ptr = (UInt64*)UnsafeUtility.Malloc(sizeof(UInt64) * bufferSize, ???, Unity.Collections.Allocator.Persistent);
    4.       UnsafeUtility.MemClear(ptr, sizeof(UInt64) * bufferSize);
    5.  
    It has to be aligned on an 8 byte boundry to ensure cross platform compatibility?
     
  5. fholm

    fholm

    Joined:
    Aug 20, 2011
    Posts:
    2,052
    If nothing else, there's a performance consideration here, from the intel x86/x64 reference manual:

     
  6. fholm

    fholm

    Joined:
    Aug 20, 2011
    Posts:
    2,052
    In case anyone looks into this, what I have found is that inside of the entities/job source code there's places where the following alignments are used: 4, 8, 16 and 64 so it seems completely fine to have alignments other than 4.