创建非通用的委托类型

时间:2013-11-02 17:25:40

标签: c# types delegates marshalling

static void CallUnmanageFunction(string dllName, string functionName, params object[] parameters)
    {
        IntPtr dllHandle = LoadLibrary(dllName);
        IntPtr functionHandle = GetProcAddress(dllHandle, functionName);
        List<Type> typeParameters = new List<Type>();
        foreach (object p in parameters)
        {
            typeParameters.Add(p.GetType());
        }
        Type type = Expression.GetDelegateType(typeParameters.ToArray());         
        Delegate function = Marshal.GetDelegateForFunctionPointer(functionHandle, type);
        function.DynamicInvoke(parameters);
    }

static void Main(string[] args)
    {
        CallUnmanageFunction("user32.dll", "MessageBoxA", IntPtr.Zero, "Es funktioniert", "Test", (uint)0);
    }

我想通过将libraryname和functionname作为字符串并将参数作为普通类型(params object []参数)来调用非托管函数。 函数“GetDelegateForFunctionPointer”需要非泛型委托类型,但“Expression”类的函数“GetDelegateType”给出通用的“Action”或“Func”-Delegate。有人想解决这个问题吗?

抱歉我的英语不好,这是我在学校最糟糕的课程。 非常感谢您的回答! :)

0 个答案:

没有答案