How do i dynamically invoke a dll method that receives a callback as parameter?

此生再无相见时 提交于 2019-12-13 07:14:55

问题


Overview:

I am writting an application to dynamically load .dlls and call their methods.

Since the .dlls are doing heavy i/o in background, i've made callbacks to notify the UI about what's happening "down there"

Pieces of Code:

            dllName = (string) e.Argument;

            // Assembling Complete path for the .dll file
            completePath       = Path.Combine(ConfigurationManager.AppSettings["DllsFolder"], dllName);
            Assembly assembler = Assembly.LoadFrom (completePath);

            // Creating Instance of Crawler Object (Dynamically)
            dllWithoutExtension = Path.GetFileNameWithoutExtension (dllName);
            Type crawlerType    = assembler.GetType (dllWithoutExtension + ".Crawler");
            object  crawlerObj  = assembler.CreateInstance (crawlerType.FullName);

            // Fetching reference to the methods that must be invoked
            MethodInfo crawlMethod       = crawlerType.GetMethod ("StartCrawling");
            MethodInfo setCallbackMethod = crawlerType.GetMethod ("SetCallback");

So far, so good. The problem is that, even tho i have declared the "callback" method

public void Notify (string courseName, int subjects, int semesters)
    {
        string course = courseName;
        int a = subjects;
        int b = semesters;
    }

This code works (just to test if the callback declaration is working)

             Crawler crawler = new Crawler();
             crawler.SetCallback (Notify);
             crawler.StartCrawling();

While this, does not work (this is what i am trying to fix. Calling the .dll method dinamically, passing the callback as argument)

setCallbackMethod.Invoke(crawlerObj, new object[] { Notify }); // this method fails, bc its a callback parameter
crawlMethod.Invoke(crawlerObj, new object[] {true}    ); // This method works, bc its a bool parameter

回答1:


I assume you have a delegate type like this for passing the method to SetCallback:

public delegate void CrawlerCallback(string courseName, int subjects, int semesters);

Then you may pass the Notify method if you cast it to this delegate type like this:

setCallbackMethod.Invoke(crawlerObj, new object[] { (CrawlerCallback)Notify });


来源:https://stackoverflow.com/questions/11037645/how-do-i-dynamically-invoke-a-dll-method-that-receives-a-callback-as-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!