开发者

Calling methods of the main program from run time loaded Dll

I have a (big and complex) C++ program with its own classes and methods.(obviously)

I would like to load at runtime a dll. From the main program i want to call a function inside the dll passing a class instance , and this function will use the method of this class.

In pseudo code

Main program:

 class MyClass{
       myattr1();
       myattr2();
       mymethod1();
       mymethod2();
 }
 
 void main(){
      MyClass* object = &(new MyClass())
      handle_of_the_dll = *some function that load the dll*
      dllfunc = getfunc(handle_of_the_dll, "interesting_function")
      dllfunc(object)
      [...etc...]

and the dll

#ifdef __cplusplus
extern C {
#endif
#ifdef BUILD_DLL
#define EXPORT __declspec(dllexport)
#else
#define EXPORT __declspec(dllimport)
#endif

#include all the needed headers from main program, where the class is defined

EXPORT void  interesting_functionn(MyClass object){
  object.mymethod1();
}
#ifdef __cplusplus
}
#endif
开发者_Go百科

Is this valid/doable/right?

EDIT:

i know that this would be a poor design for a general program, but this method is intended to give the users the ability to use their custom dll that can access the api of the main program. Something like Cpython modules


It is valid and doable. Generate a sample DLL in visual C++ and the code will have all the bases covered. Replace the static linking in the client with LoadLibrary and GetProcAdress.

Name mangling could be an issue, DependencyWalker will help you there.

Keep a low profile with emory management. For example, if you use a memory manager on one side but not on the other, your begging for trouble.


I'd say it's possible, but with all due respect, it looks like bad design to me. There is a circular dependency between the main program and the dll: the program calls functions from the dll, and viceversa. In an ideal design, the main program would consume some dll functions, and the dll wouldn't know anything about the main program, or in general, about its clients.

Perhaps you should isolate the functions from the main program that the dll needs to use in a common dll or static lib which both the program and dll use.


As long as the methods are declared virtual and you pass the object by reference or pointer there should be no problems. If however you want to access non-virtual methods of the class you will need to put it's implementation in a separate DLL.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜