Search Unity

Alternatives to using DateTime (NativeDateTime?)

Discussion in 'Entity Component System' started by JakHussain, Mar 21, 2019.

  1. JakHussain

    JakHussain

    Joined:
    Oct 20, 2016
    Posts:
    318
    So I just found out to my surprise that System.DateTime is not blitable because it contains two private const strings.

    I was wondering if anyone has come across any good alternatives that actually are blitable or if anyone has written their own alternative? I would hope to eventually see a NativeDateTime type introduced.
     
  2. M_R

    M_R

    Joined:
    Apr 15, 2015
    Posts:
    559
    const
    is not part of the data, like
    static
    .
    DateTime
    is just an
    UInt64
    .
    what makes it not blittable is the
    [StructLayout(LayoutKind.Auto)]
    attribute, telling the compiler that it can rearrange the field order.

    next question is why is a struct with a single primitive field marked as
    [StructLayout(LayoutKind.Auto)]
    ?

    btw you can make your own DateTime wrapper like we did with bool (wrapping the ticks and converting to DateTime via property / implicit conversions), until DT becomes blittable
     
  3. JakHussain

    JakHussain

    Joined:
    Oct 20, 2016
    Posts:
    318
    thats really interesting! i'm not really sure with where to start with writing a DateTime wrapper since some of these concepts are quite new to me. could you please share some code on what that might look like or a link to where I could learn more?
     
  4. M_R

    M_R

    Joined:
    Apr 15, 2015
    Posts:
    559
    it can be as simple as
    Code (CSharp):
    1. struct DTWrapper {
    2. ulong ticks;
    3. public DTWrapper(DateTime dt) => ticks = dt.Ticks;
    4. public DateTime Value => new DateTime(ticks);
    5. }
    then you can add implicit conversions, operator overloads (mirroring the original ones) etc...

    you can look at https://referencesource.microsoft.com/#mscorlib/system/datetime.cs for reference
     
    siggigg likes this.
  5. JakHussain

    JakHussain

    Joined:
    Oct 20, 2016
    Posts:
    318
    this is brilliant thanks so much!