none
MethodBody.GetILAsByteArray - is there a converse? RRS feed

  • Question

  • I am trying to find a way to populate the IL for a constructor being generated uisng ConstructorBuilder.

    We actually want to copy the IL from an existing constructor in another closely related class, we can get the IL stream for this existing constructor using GetILAsByteArray in the MethodBody class, this returns an array of bytes that represent the instruction stream.

    However, it appears that there is only one way to create the instruction stream for the new constructur and that is with Emit on the ILGenerator for the newly created constructor, but this requires explicit opcode/arg pairs to be supplied as the code is generated piece meal.

    Is there a way to simply copy a byte array of IL code straight into the constructor that is being created?

    Thanks
    H
    Sunday, December 21, 2008 12:38 PM

Answers

  • The relevant members of ILGenerator are locked up behind a pretty solid door.  You can pick the lock with Reflection.  Relevant members are EnsureCapacity(int), m_length and m_ILStream.

    While that should be enough ammo to blow your foot off, consider doing this the clean way.  If you have code that emits constructor IL for a type, surely you can re-use that code to emit IL for another type with similar constructor requirements.

    Hans Passant.
    • Marked as answer by Zhi-Xin Ye Friday, December 26, 2008 8:25 AM
    Sunday, December 21, 2008 1:41 PM
    Moderator