Hi,

The first thing you need to do is to actually create a representation
of the variable, with a proper type:

      var streamWriterTypeRef = Module.Import(typeof(System.IO.StreamWriter));
      var streamWriteCtorRef =
Module.Import(typeof(System.IO.StreamWriter).GetConstructor( new
Type[]{typeof(String), typeof(Boolean)})));

      var streamWriterVar = new VariableDefinition("writer", stream_ref);

      method.Variables.Add(streamWriterVar);

Then you can use it by either using

il.Create(OpCodes.Stloc, streamWriterVar);
il.Create(OpCodes.Ldloc, streamWriterVar);

Or, you can use the Ldloc_N version where N is the index of
streamWriterVar in the Variables collection.

Jb

On Tue, Mar 1, 2016 at 3:20 AM,  <[email protected]> wrote:
> I want to creat a new variable, for example, StreamWriter sw. I do like
> this:
>             var stream_ref = new TypeReference("System.IO",
> "StreamWriter",MethodModule, null,true);
>             var streamwriter = new VariableDefinition("writer", stream_ref);
>             method.Body.Variables.Add(streamwriter);
> and I get the NullReferenceException, I feel there lacks something, but I
> don't know where...I also wonder how to initialize the varible, like:
>             StreamWriter sw = new StreamWriter("./test.txt", true);
> and how to refer to it.
>             Before, I try to create a varible like this:
>             ins = ilProcessor.Create(OpCodes.Ldstr, @"./test.txt");
>             ilProcessor.InsertBefore(instructions[0], ins);
>             ins = ilProcessor.Create(OpCodes.Ldc_I4_1);
>             ilProcessor.InsertBefore(method.Body.Instructions[1], ins);
>             ins = ilProcessor.Create(OpCodes.Newobj,
> MethodModule.Import(typeof(System.IO.StreamWriter).GetConstructor( new
> Type[]{typeof(String), typeof(Boolean)})));
>             ilProcessor.InsertBefore(instructions[2], ins);
>             ins = ilProcessor.Create(OpCodes.Stloc_0);
>             ilProcessor.InsertBefore(instructions[3], ins);
> it doesn't work either.
> I don't know why since the IL codes dumped from the one written in C# is
> like that, I know I miss something...
> Another question is how to use the variable?
>
> --
> --
> --
> mono-cecil
> ---
> You received this message because you are subscribed to the Google Groups
> "mono-cecil" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to [email protected].
> For more options, visit https://groups.google.com/d/optout.

-- 
-- 
--
mono-cecil
--- 
You received this message because you are subscribed to the Google Groups 
"mono-cecil" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
For more options, visit https://groups.google.com/d/optout.

Reply via email to