user35443
user35443

Reputation: 6413

"AccessViolationException was unhandled" error in C# Managed Code

I have new problem. My code:

.method public static void  Main() cil managed
{
  .entrypoint
  // Code size       3 (0x3)
  .maxstack  1
  IL_0000:  ldnull
  IL_0001:  stloc.0
  IL_0002:  ret
} // end of method Program::Main

C# code:

il.Emit(OpCodes.Ldnull);
il.Emit(OpCodes.Stloc_0);
il.Emit(OpCodes.Ret);

I'm generating this code via System.Reflection and System.Reflection.Emit classes. Does anybody known why this cannot works? Please help.

My error

One small question - should I generate constructor?

Upvotes: 5

Views: 1057

Answers (1)

Andras Zoltan
Andras Zoltan

Reputation: 42353

You're trying to store a null in local 0 (stloc.0) but you don't actually have any locals defined.

You need to use the DeclareLocal method to define the local, then you can either pass that to the Emit overload that accepts a LocalBuilder (e.g. you can use that to emit the stloc opcode, followed by your LocalBuilder); or you can just carry on using stloc.0 since you know there's only one local.

Upvotes: 7

Related Questions