简体   繁体   中英

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

In the below code i am loading the dlls at runtime. But the problem here is that the aruguments of the method available in DLL are available at runtime.

eg for a method with one parameter(SetForegroundWindow) i should declare delegate int MyFunc(IntPtr a);

for a method with no parameter(GetForegroundWindow) i should declare delegate int MyFunc();

Consider the below C # code:

 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);
}





}

}

Here on Button click i want to dynamically declare the delegate and call the method at runtime as per the data from some textbox .

How can i do that

at first sight of the title, I thought to suggest using the CodeDom (and jumped in) but having looked at your code sample it looks like you are trying to import an unmanaged function from an external unmanaged library. I have not explored this any further but I am sure you would have to enclose the code block in an unsafe-statement to prevent the CLR from mangling the unmanaged memory segments.

Marshalling the parameter and return types across the CLR boundary is usually tricky - I am not sure that typeof() will do it because it will return CLR types which the external function will not understand... I could be wrong. These types are usually expressed as Windows types. This page discusses most of them: http://www.codeproject.com/Articles/66244/Marshaling-with-C-Chapter-Marshaling-Simple-Type .

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM