ヒープ上に値の型(int、byte、structs)を格納するシステムを作成しています。また、その値の型のボクシングとアンボックスを防ぐためです。これは、Unity 3Dエンジンのボクシングとアンボクシングのすべてが、大きなコードベースで大きなGC CPUスパイクを作成しているためです。VerificationException:操作により、ランタイムが不安定になる可能性があります。 EmitCall(OpCodes.Call)のトラブル
VerificationException:オペレーションがランタイムを不安定にする可能性があります。
上記の例外は、動的メソッドを呼び出そうとするとスローされます。スタックトレースは動的メソッドに入る直前に終了し、実行ポイントをブレークすることはできません。詳細は下の例で示されています。
void Main()
{
var fieldInfo = typeof(MyClass).GetMember("Number")[0] as FieldInfo;
var pointerSetFunc = CreatePointerFieldSetMethod(fieldInfo);
object myClass = new MyClass();
// The exception occurs when invoking the dynamic method.
pointerSetFunc(myClass, 0);
}
public class MyClass
{
public byte Number;
}
public static Action<object, int> CreatePointerFieldSetMethod(FieldInfo field)
{
var setMethod = new DynamicMethod("SetFieldFromPointer", typeof(void), new[] { typeof(object), typeof(int) }, true);
ILGenerator generator = setMethod.GetILGenerator();
// This returns the correct value. byte CustomBox<byte>.Unbox(Int32 index);
var unboxFunc = typeof(CustomBox<>).MakeGenericType(field.FieldType).GetMethod("Unbox", BindingFlags.Static | BindingFlags.Public);
// Somewhere in the below code the exception occurs.
generator.Emit(OpCodes.Ldarg_1); // This should be the index or "pointer" to pass into the CustomBox.Unbox function.
generator.EmitCall(OpCodes.Call, unboxFunc, null);
generator.Emit(OpCodes.Stloc_0); // This should be the result of unboxing.
// This code does not get called.
generator.Emit(OpCodes.Ldarg_0); // This should be the object MyClass.
generator.Emit(OpCodes.Ldloc_0); // This should be the value received from the CustomBox.Unbox function.
generator.Emit(OpCodes.Stfld, field); // Set the MyClass.Number field.
generator.Emit(OpCodes.Ret);
return (Action<object, int>)setMethod.CreateDelegate(typeof(Action<object, int>));
}
// The point of this class is to store values types (int, byte, struct, etc..) in an array already on the heap to avoid boxing.
// Boxing has become an issue on our application.
public struct CustomBox<T> where T : struct
{
public static T Unbox(int index)
{
// TODO: Actually make the unbox code.
return default(T);
}
}
編集: 相続人は、私が作成しようとしている方法と、それが生成されますIL:私は私が使用していた地元のdelcaringていなかったため
private static void SetFieldUsingIndex(object myClass, int index)
{
byte number = Values<byte>.Unbox(index);
((MyClass)myClass).Number = number;
}
/* Generated IL for above method.
IL_0000: nop
IL_0001: ldarg.1
IL_0002: call !0 class CPURaceTest.Values`1<uint8>::Unbox(int32)
IL_0007: stloc.0
IL_0008: ldarg.0
IL_0009: castclass CPURaceTest.MyClass
IL_000e: ldloc.0
IL_000f: stfld uint8 CPURaceTest.MyClass::Number
IL_0014: ret
*/
ローカルを使用していますが、定義していません。渡されたフィールドが 'object'に定義されていないことを確信していますので、フィールドを設定する前にターゲットインスタンスを適切な型にキャストする必要があります。 –
@BrianReichleコードを記述して逆コンパイルすると、生成されたILはローカルを宣言しないので、それは奇妙です。 OpCodes.Stloc_0はそれを私のために処理しませんか?私は既に定義されているローカル0にそれを格納するよう指定しています。 –
OpCodes.Stlocを使用する場合はローカルのみを宣言する必要はありませんが、OpCodes.Stloc_0を使用しました。 –