DLL数据共享在不同处定义效果不同..

时间:2020-12-26 05:35:20

DLL头文件:

#ifndef _DLL_SAMPLE_H
#define _DLL_SAMPLE_H

#pragma data_seg("ShareReadAndWrite")
int	DLLData = 0;
#pragma data_seg()
#pragma  comment(linker,"/SECTION:ShareReadAndWrite,RWS")

//如果定义了C++编译器,那么声明为C链接方式,
//否则编译后的函数名为?TestDLL@@YAXXZ,而并不是TestDLL
//则不能通过GetProcAddress()获取函数名,因为无法知道DLL编译后的函数名
//*******
//如果编译时用的C方式导出函数,则在导入时也要使用C方式(在应用程序#define _cplusplus)
//不然会找不到函数
//*******
#ifdef _cplusplus
extern "C" {
#endif

	//通过宏来控制是导入还是导出
#ifdef _DLL_SAMPLE
#define DLL_SAMPLE_API __declspec(dllexport)
#else
#define DLL_SAMPLE_API __declspec(dllimport)
#endif

//	DLL_SAMPLE_API extern int DLLData;

#undef DLL_SAMPLE_API

#ifdef _cplusplus
}
#endif

#endif

  

  

DLL实现

#include<objbase.h>
#define _DLL_SAMPLE	//声明是导出
#define _cplusplus	//声明为C编译方式

#ifndef _DLL_SAMPLE_H
#include "DLLSample.h"
#endif

//#pragma data_seg("ShareReadAndWrite")
//int	DLLData = 0;
//#pragma data_seg()
//
//#pragma  comment(linker,"/SECTION:ShareReadAndWrite,RWS")
//APIENTRY声明DLL函数入口点
BOOL APIENTRY DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
	switch (ul_reason_for_call)
	{
	case DLL_PROCESS_ATTACH:
	case DLL_THREAD_ATTACH:
	case DLL_THREAD_DETACH:
	case DLL_PROCESS_DETACH:
		break;
	}
	return TRUE;
}

 

 应用程序Aapp

#include<iostream>
#define _cplusplus
#include"DLLSample.h"
using namespace std;
#pragma comment(lib,"2014_4_9_DLL.lib")

int main()
{
	cout<<"DLLData:"<<DLLData<<endl;
	DLLData = 635;
	system("pause");
	return 0;
}

  

应用程序Bapp

#include<iostream>
#define _cplusplus
#include"DLLSample.h"
using namespace std;
#pragma comment(lib,"2014_4_9_DLL.lib")

int main()
{
	cout<<"DLLData:"<<DLLData<<endl;
	DLLData = 888;
	system("pause");
	return 0;
}

  

  Aapp、Bapp分别代表不同的应用程序

  Aapp A1,A2;

  Bapp B1,B2;

如果在头文件中定义数据共享

则只能A1和A2共享DLLData,B1和B2共享DLLData

如果在DLL实现部分定义数据共享(头文件需要变量导出声明)

则A1,A2,B1,B2可以共享DLLData