如何在运行时声明一个委托并在运行时在 C# 中调用其方法?

How to Declare a Delegate at runtime and call its method at runtime in C#?

在下面的代码中,我在运行时加载了 dll。 但这里的问题是,DLL 中可用的方法的参数在运行时可用。

例如,对于带有一个参数 (SetForegroundWindow) 的方法,我应该声明 委托 int MyFunc(IntPtr a);

对于没有参数的方法 (GetForegroundWindow) 我应该声明 委托 int MyFunc();

考虑以下 C# 代码:

 public partial class Form1 : Form
{

    [DllImport("kernel32.dll")]
    public static extern IntPtr LoadLibrary(string dllToLoad);

    [DllImport("kernel32.dll")]
    public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);


    [DllImport("kernel32.dll")]
    public static extern bool FreeLibrary(IntPtr hModule);


    delegate int MyFunc(IntPtr a);




   // private static extern IntPtr GetForegroundWindow();



    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {

    String strDLL = "user32.dll";
    // Load the DLL library.
    IntPtr iModule = LoadLibrary(strDLL);

    // Retrieve the function pointer.
    IntPtr pProc = GetProcAddress(iModule, "SetForegroundWindow");

      // Delegate method.

        // Convert the function pointer to delegate method.
        MyFunc pFunc = (MyFunc)Marshal.GetDelegateForFunctionPointer(pProc, typeof(MyFunc));

        // Execute the function.
        int iRes = pFunc.Invoke((IntPtr)132462);


    // Unload the DLL library.
    FreeLibrary(iModule);
}





}

}

在单击按钮时,我想根据来自某个文本框的数据动态声明委托并在运行时调用方法。

我该怎么做

乍一看标题,我想建议使用 CodeDom(并跳入),但在查看您的代码示例后,您似乎正试图从外部非托管库导入非托管函数。我没有进一步探讨这个问题,但我相信您必须将代码块包含在 unsafe-statement 中,以防止 CLR 破坏非托管内存段。

跨 CLR 边界编组参数和 return 类型通常很棘手 - 我不确定 typeof() 是否会这样做,因为它会 return CLR 类型,而外部函数不会明白...我可能是错的。这些类型通常表示为 Windows 类型。本页讨论了其中的大部分内容:http://www.codeproject.com/Articles/66244/Marshaling-with-C-Chapter-Marshaling-Simple-Type.

希望对您有所帮助。