Search Unity

generic version of StructureToPtr can't work on il2cpp build

Discussion in 'Getting Started' started by yanfei_game, Jun 22, 2020.

  1. yanfei_game

    yanfei_game

    Joined:
    May 15, 2017
    Posts:
    26
    Code (CSharp):
    1. public static void WriteMarshalUnsafe<TStruct>(TStruct structure,  byte[] bytedata)
    2. {
    3.        unsafe
    4.        {
    5.             fixed (byte* byteArrayPtr = &bytedata[0])
    6.             {
    7.                 Marshal.StructureToPtr<TStruct>(structure, (IntPtr)(byteArrayPtr), true);
    8.             }
    9.         }
    10.   }
    Above code works perfectly in mono, but when I build windows il2cpp, some error occur say that "specific object must not be a generic type" during runtime. It's weird. I used to test the generic method of StructureToPtr under il2cpp, and it works fine. I dig into https://docs.unity3d.com/Manual/ScriptingRestrictions.html, but nothing I could found about this.

    After some testing, I found the reason. When I pass any POD type as TStruct parameter, it works fine under il2cpp. But I try something hard like this(to get off GC):
    Code (CSharp):
    1. public class WrapClass<TStruct> where TStruct : struct
    2. { public TStruct data; }
    I pass the WrapClass instance to WriteMarshalUnsafe, and the error occur under il2cpp.
    If the structure parameter is an instance of a generic type(like WrapClass), it can't work.

    I have test it on Unity 2019.3.5, Unity 2020.2.0a13.
     
    Last edited: Jun 23, 2020
  2. JoshPeterson

    JoshPeterson

    Unity Technologies

    Joined:
    Jul 21, 2014
    Posts:
    6,931
    Which version of Unity are you using? If possible, please use the latest version of 2020.1 or 2020.2. We've fixed a few issues similar to this. If it still happens with the latest version, please submit a bug report. Thanks!
     
  3. yanfei_game

    yanfei_game

    Joined:
    May 15, 2017
    Posts:
    26
    @JoshPeterson Thanks for reply. It realy help. I used Unity 2019.3.5.0f1. I will test it on Unity 2019.4lts,and 2020.2.
     
  4. yanfei_game

    yanfei_game

    Joined:
    May 15, 2017
    Posts:
    26
    @JoshPeterson I test it in unity 2020.2.0a13.1691, still can't work, the error say "the specified object must not be an instance of a generic type".
     
  5. yanfei_game

    yanfei_game

    Joined:
    May 15, 2017
    Posts:
    26
    When you past a simple POD struct(not generic instance) to StructureToPtr, it call GC. Actually, generic version of StructureToPtr just call StructureToPtr(object t, ....). So, if you pass a struct to StructureToPtr, and it doesn't call GC(actually it does),then we don't need a WrapClass.
     
    Last edited: Jun 23, 2020