Search Unity

System says struct is blittable, unity say's struct isn't blittable

Discussion in 'Entity Component System' started by dara_rw, Nov 29, 2018.

  1. dara_rw

    dara_rw

    Joined:
    Jul 17, 2018
    Posts:
    2
    Heyjo,
    I have created a struct like this:

    Code (CSharp):
    1. [StructLayout(LayoutKind.Sequential)]
    2. public struct Foo
    3. {
    4.     public int i;
    5.  
    6.     [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
    7.     public int[] bar;
    8. }
    This should be a blittable struct. I checked that with the following function. (thanks to StackOverflow):

    Code (CSharp):
    1. public static class BlittableHelper<T>
    2.     {
    3.         public static readonly bool IsBlittable;
    4.  
    5.         static BlittableHelper()
    6.         {
    7.             try
    8.             {
    9.                 // Class test
    10.                 if (default(T) != null)
    11.                 {
    12.                     // Non-blittable types cannot allocate pinned handle
    13.                     GCHandle.Alloc(default(T), GCHandleType.Pinned).Free();
    14.                     IsBlittable = true;
    15.                 }
    16.             }
    17.             catch { }
    18.         }
    19.     }
    In addition the call:

    Code (CSharp):
    1. Debug.Log(BlittableHelper<Foo>.IsBlittable);
    The debugger gives me back true. So far so good. But now when I try to put this struct in a NativeList, the NativeList tells me that this struct is not blittable.

    Code (CSharp):
    1. NativeList<Foo> t = new NativeList<Foo>(10, Allocator.Persistent);
    What am I doing wrong? Does anyone have an idea?
     
  2. julian-moschuering

    julian-moschuering

    Joined:
    Apr 15, 2014
    Posts:
    529
    From the Stackoverflow entry you got this from: Note that this won't work on Mono, because GCHandle.Alloc doesn't throw an exception for non blittable types.

    A reference to a managed array is not blittable.

    Using C# 7.3 you could make your check at compile time. The unmanaged generic constraint only matches blittable types:
    Code (CSharp):
    1. public static class BlittableHelper<T> where T : unmanaged
    2. {
    3.     public static readonly bool IsBlittable = true;
    4. }
    5.  
     
  3. tertle

    tertle

    Joined:
    Jan 25, 2011
    Posts:
    3,761
    Unity has a built in method for checking Blittable (which is what NativeList uses)

    UnsafeUtility.IsBlittable<T>()


    The first require to determine if something is Blittable in Unity ECS is if it is a struct.
    Arrays are not.
     
    Last edited: Nov 29, 2018
    nyanpath and starikcetin like this.
  4. Menyus777

    Menyus777

    Joined:
    Jun 11, 2017
    Posts:
    30
    Not all unmanaged types are blittable e.g. bool