Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# MSIL存储要返回的结构值_C#_.net_Cil_Il - Fatal编程技术网

C# MSIL存储要返回的结构值

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

我正在使用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.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);