我如何动态调用接收回调作为参数的dll方法? [英] How do i dynamically invoke a dll method that receives a callback as parameter?

查看:160
本文介绍了我如何动态调用接收回调作为参数的dll方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

概述

我正在编写一个应用程序以动态加载.dll并调用其方法。

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

由于.dlls在后台执行重i / o,我已经做了回调,通知UI发生了什么下来

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

代码段

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

此代码适用于测试回调声明是否正常工作。 p>

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

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

虽然这不工作(这是我想要解决的。 dinamically,传递回调作为参数)

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


推荐答案

我假设你有一个这样的委托类型传递方法到 SetCallback

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

然后,您可以传递 Notify 方法if你把它转换为这个委托类型,如下:

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

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

这篇关于我如何动态调用接收回调作为参数的dll方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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