Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emit local variable and assign a value to it

I'm initializing an integer variable like this:

LocalBuilder a = ilGen.DeclareLocal(typeof(Int32));

How can I access it and assign a value to it? I want to do something like this:

int a, b;
a = 5;
b = 6;
return a + b;
like image 929
Seishin Avatar asked Mar 07 '13 18:03

Seishin


People also ask

How do you assign a local variable?

local - Assign a local variable in a function qsh uses dynamic scoping, so that if you make the variable alpha local to function foo, which then calls function bar, references to the variable alpha made inside bar will refer to the variable declared inside foo, not to the global variable named alpha.

Can we change value of local variable?

Updating a Variable ValueThe type of a local variable can change if it is saved into from a component within an interface. The variable will now be of the same type as the new value that was saved into it. In this example, local! number starts out as an Integer.

What is a local variable in Visual Basic?

A local variable is one that is declared within a procedure. A member variable is a member of a Visual Basic type; it is declared at module level, inside a class, structure, or module, but not within any procedure internal to that class, structure, or module.


1 Answers

Use the Ldloc and Stloc opcodes to read and write local variables:

LocalBuilder a = ilGen.DeclareLocal(typeof(Int32));
LocalBuilder b = ilGen.DeclareLocal(typeof(Int32));
ilGen.Emit(OpCodes.Ldc_I4, 5); // Store "5" ...
ilGen.Emit(OpCodes.Stloc, a);  // ... in "a".
ilGen.Emit(OpCodes.Ldc_I4, 6); // Store "6" ...
ilGen.Emit(OpCodes.Stloc, b);  // ... in "b".
ilGen.Emit(OpCodes.Ldloc, a);  // Load "a" ...
ilGen.Emit(OpCodes.Ldloc, b);  // ... and "b".
ilGen.Emit(OpCodes.Add);       // Sum them ...
ilGen.Emit(OpCodes.Ret);       // ... and return the result.

Note that the C# compiler uses the shorthand form of some of the opcodes (via .NET Reflector):

.locals init (
    [0] int32 a,
    [1] int32 b)

ldc.i4.5 
stloc.0 
ldc.i4.6 
stloc.1 
ldloc.0 
ldloc.1 
add 
ret 
like image 105
Michael Liu Avatar answered Sep 17 '22 17:09

Michael Liu