views:

286

answers:

3

Hello,

I have a problem concerning the export/import of a global variable in a DLL. I have a static library which contains a global variable such as :

In the header :

#ifdef _ENGINE_EXPORTS
extern __declspec(dllexport) Globals data;
#else
extern __declspec(dllimport) Globals data;
#endif

In the source file :

#ifdef _ENGINE_EXPORTS
__declspec(dllexport) Globals data;
#else
__declspec(dllimport) Globals data;
#endif

This global variable is exported in a DLL which links against this static library. I can see the exported symbol using DLL Export Viewer. My problem is that I want to use this global variable in another DLL and that they share the data. Right now, the same symbol is also exported in the DLL (I can see it too) and thus they have different addresses. I would like that in this other DLL, the global variable is the same as in the first DLL.

Thanks.

A: 

The following MSDN documentation topic describes how to place data in a shared segement:
How do I share data in my DLL with an application or with other DLLs?

roland
I found this page but I wanted a simple solution.
speps
A: 

In the project, one DLL is at the root of all the others so I exported the symbol in this one and it seemed to work.

speps
A: 

From your description I understand that you have two different DLLs which both export the global variable data.
When a DLL exports a variable this DLL allocates memory to the content of this variable and offers to other SW parts in the same process (e.g. to the application which loaded the DLL) to use this memory via the variable name. So if you export data from both DLLs both DLLs allocate memory and both offer in their context the variable name data (you can imagine this as two variables with the same name, but in different namespaces).
What you want to do, is that one DLL exports the data and the other DLL imports this variable. With this (dllimport) you declare the variable name without defining (and thus without allocating memory for) it.
So taken this static library from you question as static.hpp, static.cpp and static.lib:
you have dll_1.cpp (linked against static.lib)

#define _ENGINE_EXPORTS (1)
#include "static.h"
__declspec(dllexport) int getAdrAsInt_1()
{
    return (int)&data;
}

and dll_2.cpp (linked against the "import library" of dll_1, see here )

// here without _ENGINE_EXPORTS to use dllimport instead of dllexport
#include "static.h"
__declspec(dllexport) int getAdrAsInt_2()
{
    return (int)&data;
}

Another way to access data in dll_1 from dll_2 would be to use from dll_2, GetProcAddress. But then you need the HMODULE from the LoadLibrary-call to load dll_1.

BTW: As I understand your situation "How do I share data in my DLL with an application or with other DLLs?" is not applicable, because it describe a complete different scenario.

felix0322