李国帅 于2011.4编写
两个程序同时使用同一个VC动态链接库,全局变量是否相互影响
1建立动态库
#include <windows.h> #ifdef _MANAGED #pragma managed(push, off) #endif int nvar = 100; BOOL APIENTRY DllMain( HMODULE hModule,DWORD ul_reason_for_call,LPVOID lpReserved) { return TRUE; } #ifdef _MANAGED #pragma managed(pop) #endif __declspec(dllexport) void SetVar(int n){nvar = n;}; __declspec(dllexport) int GetVar(){return nvar;};
2\编译动态库
3\引用动态库
#include <windows.h> #include <iostream> using namespace std; #pragma comment(lib,"d:\\MMP\\debug\\DllTest.lib") __declspec(dllimport) void SetVar(int n); __declspec(dllimport) int GetVar(); int main() { //SetVar(100000); cout<<GetVar()<<endl; system("pause"); return 0; }
4\测试
第一次编译,使用SetVar(100000);把变量改为100000,然后编译出来的exe改名。
第二次取消SetVar(100000);重新编译。
同时运行两个exe,后者运行后得到100,前者为100000。
结果它们之间不影响,它们不共享内存空间。
5\如何共享
要想使用共享空间必须申请明确
#pragma data_seg("Shared") long g_nCount = 0; #pragma data_seg() #pragma comment(linker, "/Section:Shared,rws") __declspec(dllexport) void SetCount(int n) { InterlockedExchangeAdd(&g_nCount, n); //HANDLE g_hMutex = CreateMutex(NULL,FALSE,"MutexCount"); //WaitForSingleObject(g_hMutex, INFINITE); //g_nCount = n; //ReleaseMutex(g_hMutex); }; __declspec(dllexport) int GetCount() { int ncount = InterlockedExchangeAdd(&g_nCount, 0); return ncount; }; __declspec(dllimport) void SetCount(int n); __declspec(dllimport) int GetCount();
然后重新测试
//SetCount(100000);
cout<<GetCount();