c++ - Instantiate a class in exported DLL function using getProcAddress -


i have following .h code dll , using getprocaddress consume dll in code.

// mathfuncsdll.h  #ifdef mathfuncsdll_exports #define mathfuncsdll_api __declspec(dllexport)  #else #define mathfuncsdll_api __declspec(dllimport)  #endif  namespace mathfuncs {     // class exported mathfuncsdll.dll     class mymathfuncs     {     public:         int x = 10;         mymathfuncs();             // returns + b + x            mathfuncsdll_api double add(double a, double b);       }; } 

and corresponding .cpp code

// mathfuncsdll.cpp : defines exported functions dll application.  //  #include "stdafx.h" #include "mathfuncsdll.h" #include <stdexcept>  using namespace std;  namespace mathfuncs {     mymathfuncs ::mymathfuncs()     {             x = 10;     }      double mymathfuncs::add(double a, double b)     {         return + b + x;     }  } 

the function add exported , adds , b along initial value of x = 10.

i have created dll file of same , calling functions using loadlibrary , getprocaddress.

the code works fine when not use constructor , directly add 10 i.e + b + 10. fails when + b + x, , constructor not called.

how instantiate such object using getprocaddress when load dll , call function instantiated object method.

calling constructor not automatic. taken care of c++ compiler when use operator new no longer being done. have use getprocaddress() constructor address , invoke it.

and before that, have allocate memory object. address pass constructor. gets difficult, have no idea how memory allocate. guessable simple class 1 optimizations applied c++ compiler when class has virtual methods or implements multiple inheritance rapidly make unpractical.

this big reason interop c++ difficult , poorly supported other language runtimes. reliable way export class factory function, simple function uses new operator create object , return pointer. there's problem destroying object, need kind of memory manager ensures correct implementation of operator delete called well. typically done reference counting, std::shared_ptr<>.

all , all, you'll on way re-inventing com.


Comments

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

delphi - Dynamic file type icon -