Access a global variable in a dll

2019-08-07 15:06发布

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.

2条回答
Deceive 欺骗
2楼-- · 2019-08-07 15:45

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.

查看更多
来,给爷笑一个
3楼-- · 2019-08-07 16:07

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:

CRITICAL_SECTION *gCS;

__declspec(dllexport) void MyDLL_SetCS(CRITICAL_SECTION *cs) {
  gCS = cs;
}

Application:

CRITICAL_SECTION cs;
// initialize cs here
MyDLL_SetCS(&cs);

Then the DLL can use its own copy of the pointer when required.

查看更多
登录 后发表回答