The following program crashes with an exception for me. Is there
something I’m doing wrong?

I suspect it’s a bug in Mono.Cecil because I’m getting various other
exceptions for more complex input assemblies. In the case below, the
error is that ByteBuffer::ReadBytes() is called with a “length”
parameter set to 163338, which larger than the buffer size, 4608.
Other times, a NotSupportedException is thrown in
CodeReader::PatchRawMethodBody() because the “flags” variable is 0.

Also, the exception only occurs during the second call to
AssemblyDefinition.Write() — if I omit the first one, the second one
no longer throws.

Many thanks for any help you could provide!

(Also, as an aside, how do I easily download the newest version? It
seems that the github page (http://github.com/jbevain/cecil/downloads)
lists version 0.9.2 as the newest, but it’s already outdated: for
example, it doesn’t have the Instruction::ToString() method.)

------------------------------------------------------------------------
using System.Linq;
using Mono.Cecil;

namespace Timwi.Temp
{
    class X
    {
        public class Y { }
        public class Z { }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var asm =
AssemblyDefinition.ReadAssembly(System.Reflection
                .Assembly.GetExecutingAssembly().Location);
            var nestedType = asm.MainModule
                .Types.Single(t => t.FullName == "Timwi.Temp.X")
                .NestedTypes.Single(nt => nt.Name == "Y");
            unnest(asm, nestedType, 1);
            nestedType = asm.MainModule
                .Types.Single(t => t.FullName == "Timwi.Temp.X")
                .NestedTypes.Single(nt => nt.Name == "Z");
            unnest(asm, nestedType, 2);
        }

        private static void unnest(AssemblyDefinition asm,
            TypeDefinition nestedType, int i)
        {
            var outerType = nestedType.DeclaringType;
            outerType.NestedTypes.Remove(nestedType);
            nestedType.DeclaringType = null;
            asm.MainModule.Types.Add(nestedType);
            nestedType.IsPublic = true;
            asm.Write(@"CecilOutput." + i + ".exe");
        }
    }
}

-- 
--
mono-cecil

Reply via email to