C# MSIL存储要返回的结构值
我正在使用RemotingLite库(),代理类工厂有问题。 简而言之,问题在于为返回C# MSIL存储要返回的结构值,c#,.net,cil,il,C#,.net,Cil,Il,我正在使用RemotingLite库(),代理类工厂有问题。 简而言之,问题在于为返回ValueType对象(如用户定义的结构)生成代码时 这里是原始代码的一部分: ... mIL.Emit(OpCodes.Ldloc, resultLB.LocalIndex); //load the result array mIL.Emit(OpCodes.Ldc_I4, 0); //load the index of the return value. Alway 0 mIL.Emit(OpCodes.L
ValueType
对象(如用户定义的结构)生成代码时
这里是原始代码的一部分:
...
mIL.Emit(OpCodes.Ldloc, resultLB.LocalIndex); //load the result array
mIL.Emit(OpCodes.Ldc_I4, 0); //load the index of the return value. Alway 0
mIL.Emit(OpCodes.Ldelem_Ref); //load the value in the index of the array
if (returnType.IsValueType)
{
mIL.Emit(OpCodes.Unbox, returnType); //unbox it
mIL.Emit(ldindOpCodeTypeMap[returnType]);
}
else
mIL.Emit(OpCodes.Castclass, returnType);
}
mIL.Emit(OpCodes.Ret);
ldindOpCodeTypeMap
是一个包含操作码的字典,如opcode.Ldind_U2
等。因此它只适用于标准MSIL类型,如Int16、Int32
等。但是如果我需要推到堆栈,然后返回自定义的ValueType
值(例如-Guid
,大小为16字节),我需要做什么
例如:
...
mIL.Emit(OpCodes.Unbox, returnType); //unbox it
OpCode opcode;
if (ldindOpCodeTypeMap.TryGetValue(returnType, out opcode))
{
mIL.Emit(ldindOpCodeTypeMap[returnType]);
}
else
{
// here I getting the size of custom type
var size = System.Runtime.InteropServices.Marshal.SizeOf(returnType);
// what next?
}
...
这里我得到了自定义ValueType
value的大小。那么,如何像Ldind\ucode>x操作码那样间接地将自定义ValueType
的值加载到求值堆栈中呢?
谢谢 Ldobj会做你想做的事。但您也可以用Unbox_Any替换整个条件:它将完成值类型或引用类型所需的所有操作
完全替换您发布的代码将是:
...
mIL.Emit(OpCodes.Ldloc, resultLB.LocalIndex); //load the result array
mIL.Emit(OpCodes.Ldc_I4, 0); //load the index of the return value. Alway 0
mIL.Emit(OpCodes.Ldelem_Ref); //load the value in the index of the array
mIL.Emit(OpCodes.Unbox_Any, returnType);
mIL.Emit(OpCodes.Ret);