-1

So i have something like this

public void test(string name, Func<object> fuc)
    {
        object x = fuc();
        FieldInfo fdt = Dest.GetField(nameDest, BindingFlags.NonPublic | 
        BindingFlags.Public | BindingFlags.Instance);

        ilGenerator.Emit(OpCodes.Ldarg_0);
        ilGenerator.Emit(OpCodes.Ldfld, fieldBuilder);

        //and here i want to load the x

        ilGenerator.Emit(OpCodes.Stfld, fdt);
    }

Can someone help me plz? Thank you

1 Answers1

1

You can't. Depending on how and when the IL you generated is invoked, the object might not be accessible (e.g. you could save the IL to an assembly and use it from a separate process).

What you need is some code that can restore the object. You might be able to do that by saving the object to a field (probably a static one) and then loading that, if the IL is only used in the current process/app domain.

Another option would be to use some kind of serialization to save the object and then deserialize it in your IL, assuming the object can be serialized.

svick
  • 236,525
  • 50
  • 385
  • 514
  • Also, that static field can be a Dictionary, the key can be a lock-free-incremented integer used as an Object ID, and the value can be the object you need. This works since ints CAN be hardcoded in the source, unlike whole objects. So you just push the int key onto the stack at compile time and then call the dictionary's indexer to fetch the object. – hoodaticus Jun 15 '17 at 17:25