Emit local variable and assign a value to it

僤鯓⒐⒋嵵緔 提交于 2019-12-05 16:56:50

问题


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;

回答1:


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 


来源:https://stackoverflow.com/questions/15278566/emit-local-variable-and-assign-a-value-to-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!