Send data back to .exe from dll

2020-07-26 04:03发布

问题:

I am developing a plug-in based application and need to be able to post data (strings, arrays) back to my main EXE when something happens. I'm not quite sure how to go about this, I have thought about creating a thread in the main application that would continuously call a method in the DLL asking for data but this seems very inefficient, is there some sort of event listener I could use for this?

Thanks.

回答1:

As part of the loading mechanism for the plug-in DLLs, you could pass in a class object / function pointer / delegate / event that the DLL can use to inform the main application of any events the plug-in generates.



回答2:

Instead of polling the DLL, you should consider using a form of Inversion of Control.

This can be as simple as exposing an event in the dll that your exe subscribes to, or passing in an object (or interface) to the DLL which it can use to call methods to notify your executable, etc. There are many options here, and its difficult to know the best without more information about your architecture.



回答3:

You can use Delegates/Events on your DLL and subscribe with your EXE ?



回答4:

Let's set some baselines...

  • EXE runs
  • EXE loads a DLL containing plugins
  • EXE instantiates a type (the "plugin")
  • Plugin starts waiting for an event
  • EXE waits
  • External event (on another thread) is noted by the plugin instance
  • EXE is notified of the event

If this is the case, the simplest thing is to define an event in your plugin type.

public interface IPlugin
{
  public event EventHandler SomethingHappened;
  public void StartWatchingForSomething();
}

where the code would be something like...

public static void Main()
{
  foreach (var plugin in LoadAllPluginTypes()) // IoC container, MEF, something
  {
    plugin.SomethingHappened += SomethingHappenedEventHandler;
    plugin.StartWatchingForSomething();
  }

  public void SomethingHappenedEventHandler(object sender, EventArgs e)
  { 
    //derp
  }
}

Please note, the event handlers are going to be firing on the same thread as the notification comes in on. For example, if your plugin is responding to file system events (via the FileSystemWatcher), the event handlers will be firing on the same thread as the thread that's executing code "defined in the dll".

If your EXE is a winforms or WPF project, you'll have to do an Invoke or Dispatcher.Invoke to get on the UI thread before updating any visual controls.



回答5:

If it's a managed DLL (C# ,VB ,CLI/C++ with ref classes )

Reference the DLL in the project's references.

Right click on project -> Add reference -> Browse -> Choose the file.

After you do that you should get the API, and use it in a normal C# way.

The namespaces declared in the DLL will be accessible, and all the objects as well.