a DLL need to access symbols of its application

2019-04-11 08:24发布

问题:

In C++, is it possible for a DLL to access some symbols of the application that loaded it ? I have an application that load plug-ins (dll), and these plug-ins need to access some API of the application.

Is it possible to achieve this without creating a new DLL that share this API ?

Is a struct of function pointers suitable in this situation ?

example: a bool Log(char*) function defined in the host application and a plug-in that need to log some events.

回答1:

Another vote for passing a callback interface into the plug-in DLL. I.e. the callback interface...

class IHostApplication
  {
  public:
    virtual bool Log(const wchar_t* ip_log_string) = 0;
  };

The DLL plugin interface

class IPlugin
  {
  public:
    virtual void InitializePlugin(IHostApplication *ip_host) = 0;
  };

The host would load the plug-in DLL (dynamically if necessary), and then pass itself as an IHostApplication* to the plugin, enabling any callback you might want.



回答2:

It's possible, but your design choice is questionable.

An EXE can export functions in the same way a DLL can, so you can use GetProcAddress in the way you're familiar with.

However, why have you designed it so that plugins need to know anything about the host program's internal functions? It should be the other way around.

The host should require that plugins implement a set of routines (which they export), adhering to a particular contract. As part of their interface, the host could pass them host-specific information in a pointer to a struct (say, version info, capabilities) and the like, if necessary.

The plugins should not be attempting to acquire function pointers to the host module.



回答3:

Callback function pointer, list of callback function pointers, or pointer to callback interface - I would use one of these options. Dll client must implement callback interface and pass pointer to this interface to dynamically created Dll. Dynalically created Dll keeps this pointer, and calls its functions when necessary, for example, to report some events.



标签: c++ dll