Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

321
Visualizações
¿Cómo puedo cambiar el valor del campo con Mono Cecil?

Tengo un programa C# y tiene una clase:

 public class Test { internal const string a = "some value"; private DateTime b = new DateTime(); }

¿Cómo puedo usar Mono Cecil para cambiar su valor inicial para que se vea así?

 public class Test { internal const string a = "test"; private DateTime b = DateTime.MaxValue; }

En este momento solo tengo el siguiente código esqueleto y no sé cómo modificar los campos.

 void Main() { var input = @"C:\my_projects\a.exe"; var asm = AssemblyDefinition.ReadAssembly(input); foreach (ModuleDefinition module in asm.Modules) { foreach (TypeDefinition type in module.GetTypes()) { foreach (var field in type.Fields) { if (field.Name == "a") { } else if (field.Name == "b") { } } } } asm.Write(@"c:\my_projects\b.exe"); }
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Descargo de responsabilidad

Código muy frágil por delante

Para la constante es cuestión de establecer la propiedad fld.Constant .

Para campos estáticos/de instancia, el compilador de C# emitirá el código de inicialización en el constructor, por lo que deberá encontrar la instrucción que está cargando el valor que se almacenará en el campo y reemplazarlo.

 using System.IO; using System.Linq; using Mono.Cecil; using Mono.Cecil.Cil; namespace x { class Program { public const string ConstValue = "old"; public int instanceField = 1; static void Main(string[] args) { var o = new Program(); if (o.instanceField == 1) { using var a = AssemblyDefinition.ReadAssembly(typeof(Program).Assembly.Location); var t = a.MainModule.Types.Single(ct => ct.Name == "Program"); var constant = t.Fields.First(f => f.Name == "ConstValue"); constant.Constant = "new value"; var ctor = t.Methods.Single(m => m.IsConstructor); System.Console.WriteLine(ctor); var il = ctor.Body.GetILProcessor(); var inst = il.Body.Instructions.First(); while (inst != null) { System.Console.WriteLine($"Checking {inst}"); if (inst.OpCode == OpCodes.Stfld && ((FieldReference) inst.Operand).Name == "instanceField") { // notice that this is very fragile. For this specific // case I'd say it is safe but depending on how you // initialize the field the instruction that loads // the value to be assigned to the field may be located // several instructions prior to the actual assignment // but you can keep track of the stack state and figure // out which instruction is pushing the value that // will end up being poped into the field. il.Replace(inst.Previous, il.Create(OpCodes.Ldc_I4, 42)); System.Console.WriteLine("Found"); break; } inst = inst.Next; } var p = typeof(Program).Assembly.Location; var newBinaryPath = Path.Combine(Path.GetDirectoryName(p), Path.GetFileNameWithoutExtension(p) + "2" +Path.GetExtension(p)); a.Write(newBinaryPath); System.Console.WriteLine($"New binary writen to {newBinaryPath}"); } System.Console.WriteLine(o.instanceField); // Notice that no matter what you do, this will always print the // old value; that happens because the C# compiler will emit the // constant at the call site (instead of referencing the field // at runtime) System.Console.WriteLine(ConstValue); } } }
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda