dimanche 31 janvier 2016

C# Reflection issue - second method call

I'm trying to dynamically wrap c++ function in c# using reflection. Everything works fine. But when I try to add another call after c++ function, it doesn't call it.

private static Delegate GetDebugDelegate(IntPtr ptr, Type delType)
{
    MethodInfo info = delType.GetMethod("Invoke");
    Type returnType = info.ReturnType;
    ParameterInfo[] parameters = info.GetParameters();
    Type[] parameterTypes = parameters.Select(i => i.ParameterType).ToArray();
    Type[] parameterTypesPointers = parameterTypes.Select(i => i.GetPointerType()).ToArray();

    var dm = new DynamicMethod($"{delType.Name}Calli", returnType, parameterTypes, delType, true);

    ILGenerator il = dm.GetILGenerator();

    for (int i = 0; i < parameterTypesPointers.Length; i++)
        il.Emit(OpCodes.Ldarg, i);

    if (IntPtr.Size == 4)
        il.Emit(OpCodes.Ldc_I4, ptr.ToInt32());
    else if (IntPtr.Size == 8)
        il.Emit(OpCodes.Ldc_I8, ptr.ToInt64());
    else
        throw new PlatformNotSupportedException();

    il.EmitCalli(OpCodes.Calli, CallingConvention.Cdecl, returnType.GetPointerType(), parameterTypesPointers);
    il.Emit(OpCodes.Ret);

    //This does not gets called
    Action action = () =>
    {
        Console.WriteLine("test");
    };
    il.Emit(OpCodes.Call, action.Method);
    il.Emit(OpCodes.Ret);

    return dm.CreateDelegate(delType);
}

Here's some decompiled il for delegate 'public delegate uint Temp(int type);'

    .method public static uint32 TempMethod(int32) cil managed
    {
        .maxstack 2
        L_0000: ldarg A_0
        L_0004: nop 
        L_0005: nop 
        L_0006: ldc.i4 0x5aa166c0
        L_000b: calli method unmanaged cdecl uint32 *(int32)
        L_0010: ret 
        L_0011: call instance void [Test]Test.TestClass/<>c::<TestSave>b__4896_0()
        L_0016: ret 
    }

My best guess is that i have to store return value, call second method and then return, but i dont know how.





Aucun commentaire:

Enregistrer un commentaire