Search Unity

Issue on Android Device only ( Marshal.StructureToPtr )

Discussion in 'Scripting' started by Enfusion, Feb 16, 2020.

  1. Enfusion

    Enfusion

    Joined:
    Aug 10, 2018
    Posts:
    3
    Hello guys,

    im pretty new to android game development and im not really sure how to debug in a proper way.
    It seems to be a bit handy to play with values and checking stuff on the acuall mobile device.
    Anyways... Im convertig a Structure to an ByteArray which works well on the Unity Debugger but as soon
    as i move the app to the android device, im getting a Object Reference Error within this function:

    Code (CSharp):
    1. public static Byte[] StructureToByteArray(Object obj)
    2.  {
    3.         try
    4.         {
    5.             Int32 rawsize = Marshal.SizeOf(obj);
    6.             IntPtr buffer = Marshal.AllocHGlobal(rawsize);
    7.             Marshal.StructureToPtr(obj, buffer, false);              // This function throws the exception
    8.             Byte[] rawdatas = new Byte[rawsize];
    9.             Marshal.Copy(buffer, rawdatas, 0, rawsize);
    10.             Marshal.FreeHGlobal(buffer);
    11.             return rawdatas;
    12.         }
    13.         catch (Exception e)
    14.         {
    15.             UE.Debug.Log(e.Message);
    16.         }
    17.         return null;
    18.  
    19.     }
    I already did a research on google but i dont found threads about marshal issues on android.
    The object is not the issue and gets delivered how it should.

    My guess: It is may related to the static unsafe void Copy function or some Windows Only Code within this function which can not work on android, but this is above my knowledge..

    Can somebody help me with this issue?
     
    Last edited: Feb 16, 2020
    filip-mixedworld likes this.
  2. Enfusion

    Enfusion

    Joined:
    Aug 10, 2018
    Posts:
    3
    Edit: The Issue is related to a char array within a struct.
    Integer values seems to work but as soon as i add a string or char array to the structure i get the
    reference error on android.

    This is part of my Structure and as soon as i remove it, the error is gone:

    Code (CSharp):
    1.  [MarshalAs(UnmanagedType.ByValArray, SizeConst = 300)]
    2.     public Char[] szStringDataA = new Char[300];
    Sadly i rely on theese strings since they contain important packet informations.