Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

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

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...