0

I all, I have a win32 application and several DLLs that must use a global variable. In each dll I put

extern MYTYPE* myvariable = NULL;

and in the main program I have

MYTYPE* myvariable = NULL;
mavariable = new MYTYPE();
....

now, when the DLLs are loaded myvariable is NULL and I cannot use it. How can I share the instance of the main program with all the DLLs?

Stefano
  • 3,213
  • 9
  • 60
  • 101
  • A DLL cannot import a variable (or function) from an EXE. Mystery number 1 to solve is how you got the DLL to link. – Hans Passant Feb 23 '11 at 19:22
  • I linked the DLLs to the win32 program and I would use a global variable that is defined in another DLL but that must be initialized in the program so that all the other dlls can use it – Stefano Feb 23 '11 at 19:29

2 Answers2

1

You should make some changes in your program. If it is possible you can just move myvariable from the EXE to one from DLL. Then you can continue to use import libraries.

It general you can export functions or data from an EXE, but in the most cases there are less sense to do this. So you can see this very seldom. For example WinWord.exe or Excel.exe do this.

If really need to export frunction or data from EXE and use it in the DLL you should use dynamical binding with respect of GetProcAddress and GetModuleHandle(NULL). You can do such kind of manual binding inside of DllMain. The address of myvariable of the EXE you can save in the local myvariable of the DLL.

Oleg
  • 220,925
  • 34
  • 403
  • 798
  • the real variable is declared in a DLL and defined in the the others as extern. In the main I need to initialize the variable in the dll and in the other dlls I could call a method that get the variable instance – Stefano Feb 24 '11 at 11:41
  • @Stefano: In the text of your question you wrote that "In each dll I put extern MYTYPE* myvariable = NULL". So in every DLL you have **separate** variable. You should remove initialization from all excepting one DLL which will own the variable. You should **export** the variable from the DLL and **import** the variable in all other DLLs or the EXE. Look at http://support.microsoft.com/kb/90530 which describes how you can export and import data. Read also http://msdn.microsoft.com/en-us/library/z4zxe9k8.aspx – Oleg Feb 24 '11 at 11:54
0

maybe you're looking for this: Windows & C++: extern & __declspec(dllimport)

Community
  • 1
  • 1
Kevin
  • 24,871
  • 19
  • 102
  • 158