how do I access a global variable which is initialized in the main() function of my application in a dll?
My global variable contains a critical section object which I need to lock in a dll.
I've tried to export it in my application and import it in the dll using
__declspec(dllexport)
and __declspec(dllimport)
but when I try to lock the critical section I get a runtine exception which makes me think that the variable my dll accesses is not initialized correctly.
The dll is loaded at runtime using LoadLibrary.
Any hints would be appreciated.
It's a really bad idea, since it violates the modularity principle :(
I honestly don't know how to force the compiler and linker to do what you want, if you have to, I'd rather pass a reference/pointer to such a global variable in dll initialization.
Generally variables in a DLL are accessed from the application, but it looks like you're trying to do it the other way round. And your way of exporting from application and importing in the DLL seems a bit hackish.
How about creating a function in your DLL that takes a pointer to the critical section object from your application and stores it in the DLL's own global variable?
DLL:
Application:
Then the DLL can use its own copy of the pointer when required.