具有泛型委托的C#GetDelegateForFunctionPointer [英] C# GetDelegateForFunctionPointer with generic delegate

查看:39
本文介绍了具有泛型委托的C#GetDelegateForFunctionPointer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要动态调用dll函数.

I need to dynamically invoke dll function.

我正在使用标准的Windows API加载dll并获取proc地址.

I'm using standard windows API to load dll and get proc address.

检索proc的IntPtr后,我尝试将其转换为委托:

After I retrieve proc's IntPtr I try to convert it to delegate:

Func<int> inv = (Func<int>)Marshal.GetDelegateForFunctionPointer(proc, typeof(Func<int>));

但是失败,因为typeof(Func)返回泛型类型.

But it fails because typeof(Func) return generics type.

有什么干净的方法可以完成我要完成的工作,而不仅仅是声明成员委托和用作类型吗?

Is there any clean way to accomplish what I'm trying to do without just declaring member delegate and use it as type ?

我的意思是我正在努力避免以下冗余:

I mean I'm trying to avoid the following redundancy:

//I need this member only for typeof operator
private delegate int RunDll();
RunDll inv = (RunDll)Marshal.GetDelegateForFunctionPointer(proc, typeof(RunDll));

推荐答案

如果委托类型是动态的并且您不知道参数,那会更糟.然后,您可以使用.NET方法生成它.

It would be worse if the delegate type was dynamic and you didn't know the parameters. Then you could use .NET methods to generate it.

public static class DelegateCreator
{
    private static readonly Func<Type[],Type> MakeNewCustomDelegate = (Func<Type[],Type>)Delegate.CreateDelegate(typeof(Func<Type[],Type>), typeof(Expression).Assembly.GetType("System.Linq.Expressions.Compiler.DelegateHelpers").GetMethod("MakeNewCustomDelegate", BindingFlags.NonPublic | BindingFlags.Static));

    public static Type NewDelegateType(Type ret, params Type[] parameters)
    {
        Type[] args = new Type[parameters.Length];
        parameters.CopyTo(args, 0);
        args[args.Length-1] = ret;
        return MakeNewCustomDelegate(args);
    }
}

DelegateCreator.NewDelegateType(typeof(int)) //returns non-generic variant of Func<int>

这篇关于具有泛型委托的C#GetDelegateForFunctionPointer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆