Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Issues with IL2CPP and Reflection

Discussion in 'Scripting' started by Altaf-Navalur, Nov 21, 2019.

  1. Altaf-Navalur

    Altaf-Navalur

    Joined:
    Mar 1, 2013
    Posts:
    3
    Hello Everyone,
    I am running into an issue with IL2CPP, I am using Reflection. My code is as following,
    Code (CSharp):
    1.         public static void Inject(object obj)
    2.         {
    3.             BindingManager bindingManager = GameObject.FindObjectOfType<BindingManager>();
    4.             if (bindingManager == null)
    5.                 return;
    6.             Type type = obj.GetType();
    7.             List<FieldInfo> fieldInfo = GetFields(type);
    8.             foreach (FieldInfo f in fieldInfo)
    9.             {
    10.                 Attribute[] attributes = f.GetCustomAttributes(false) as Attribute[];
    11.                 foreach (Attribute attr in attributes)
    12.                 {
    13.                     if (attr is InjectSignal)
    14.                     {
    15.                         if (bindingManager._Bindings.ContainsKey(f.FieldType))
    16.                             f.SetValue(obj, bindingManager._Bindings[f.FieldType]);
    17.                         else
    18.                             Debug.LogError("Inject-> Could not find binding for type : " + f.FieldType);
    19.                     }
    20.                 }
    21.             }
    22.         }
    In the above code, GetCustomAttributes function is returning null on the Android platform(I haven't tried iOS yet ).
    I created a link.xml as follows,

    Code (CSharp):
    1.    
    2. <?xml version="1.0" encoding="UTF-8"?>
    3. <linker>
    4.     <assembly fullname="System">
    5.         <type fullname="System.Reflection" preserve="all" />
    6.         <type fullname="System.Reflection.*" preserve="all" />
    7.         <namespace fullname="System.Reflection" preserve="all" />
    8.         <namespace fullname="System.Reflection.*" preserve="all" />
    9.     </assembly>
    10. </linker>
    11.  
    Any suggestion would be really helpful.
     
  2. palex-nx

    palex-nx

    Joined:
    Jul 23, 2018
    Posts:
    1,745
    Maybe you also should add your attributes to link.xml ?
     
  3. Altaf-Navalur

    Altaf-Navalur

    Joined:
    Mar 1, 2013
    Posts:
    3
    Thanks to my friend Sunil..
    Problem was with type casting
    Changing the following line
    Attribute[] attributes = f.GetCustomAttributes(false) as Attribute[];

    to

    object[] attributes = f.GetCustomAttributes(false);

    fixed the exception.