要想在DLL共享数据,必须重新定义一个共享段,然后用函数去修改添加
DLL代码:
#include "stdafx.h" #pragma data_seg("MyData") //定义一个共享段 int name=10; #pragma data_seg #pragma comment(linker,"/section:MyData,rws") extern "C" _declspec(dllexport) int add(void) //用函数去操作它 { return name*5; } extern "C" _declspec(dllexport) int letdown(void) { name = name - 1; return name*5; } BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: MessageBox(NULL,"DLL载入","OK",NULL); break; case DLL_PROCESS_DETACH: MessageBox(NULL,"DLL卸载","OK",NULL); break; } return TRUE;
应用程序1)
#include "stdafx.h" #include <windows.h> #include <process.h> int main(int argc, char* argv[]) { char str[] = "C:\\Documents and Settings\\Administrator\\桌面\\test\\Dlltest.dll"; FARPROC procaddress = GetProcAddress(LoadLibraryA(str),"letdown"); int recv = procaddress(); printf("name = %d\n",recv); system("pause"); return 0; }应用程序2)
#include "stdafx.h" #include <windows.h> #include <process.h> int main(int argc, char* argv[]) { FARPROC procaddress = GetProcAddress(LoadLibraryA("Dlltest.dll"),"add"); int recv = procaddress(); printf("name = %d\n",recv); system("pause"); return 0; }
效果:
先用 程序1 改变了 name值 运行后 输出9*5
然后程序2运行 如果是共享内存的话 还是输出9*5 共享成功
但如果 没有设置 #pragma data_seg 的话 每个EXE调用的DLL 都是独立的