分类: C/C++
2009-03-05 15:09:38
以创建封装内存映射文件函数的DLL为例子
简要步骤:
1.创建vmap.c
2.创建vmap.mak
3.使用make -f vmap.mak 产生dll
需要做一些准备进行下一步的具体操作
1. 下载cygwin开发环境
2. 选择安装gcc ,gnu make tool ,mingw是必须的
3.在Windows的PATH环境变量添加安装后的Cygwin下的bin目录 ,这样可以采用CMD环境
以下是具体操作
1.添加vmap.c源码
#include
#pragma data_seg ("vmap")
HANDLE hMapFile;
LPCTSTR pBuf;
#pragma data_seg ()
#pragma comment(linker,"/section:vmap,RWS")
#define BUF_SIZE 256
#define EDS_GKEY TEXT("Global\\vmapkey")
BOOL WINAPI APIENTRY DllMain(HINSTANCE hinstDll, DWORD reason_for_call, LPVOID lpReserved)
{
switch( reason_for_call )
{
case DLL_PROCESS_ATTACH:
break;
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
//创建
__declspec(dllexport) BOOL CreateMap(TCHAR *szName)
{
hMapFile = CreateFileMapping(
INVALID_HANDLE_VALUE, // use paging file
NULL, // default security
PAGE_READWRITE, // read/write access
0, // max. object size
BUF_SIZE, // buffer size
szName); // name of mapping object
if (hMapFile == NULL)
{
return 1;
}
pBuf = (LPTSTR) MapViewOfFile(hMapFile, // handle to map object
FILE_MAP_ALL_ACCESS, // read/write permission
0,
0,
BUF_SIZE);
if (pBuf == NULL)
{
CloseHandle(hMapFile);
return 2;
}
return 0;
}
//读写 ,nrw=1时写入 ,0时读
__declspec(dllexport) char* ReadWriteMap(TCHAR *szName ,TCHAR *szMsg ,int nrw)
{
hMapFile = OpenFileMapping(
FILE_MAP_ALL_ACCESS, // read/write access
FALSE, // do not inherit the name
szName); // name of mapping object
if (hMapFile == NULL)
{
return "";
}
pBuf = (LPTSTR) MapViewOfFile(hMapFile, // handle to map object
FILE_MAP_ALL_ACCESS, // read/write permission
0,
0,
BUF_SIZE);
if (pBuf == NULL)
{
CloseHandle(hMapFile);
return "";
}
if (nrw == 1)
{
CopyMemory((PVOID)pBuf, szMsg, (strlen(szMsg) * sizeof(TCHAR)));
}
return (char*)pBuf;
}
//关闭
__declspec(dllexport) void CloseMap(void)
{
UnmapViewOfFile((LPVOID)pBuf);
CloseHandle(hMapFile);
}
2. vmap.mak文件内容
vmap.dll: vmap.c 后面的行第一个字符一定是一个TAB 。-mno-cygwin参数代码纯API,摆脱cygwin1.dll
vmap.dll: vmap.c
gcc -DBUILD_DLL -c vmap.c;
gcc -shared -o vmap.dll vmap.o -Wl,--out-implib,vmaplib.a -mno-cygwin
3. 测试vmap.dll的代码 ,使用Visual Foxpro9测试
在第一个VFP进程中创建MAP并写入当前日期
declare string ReadWriteMap in vmap.dll string @ ,string @ ,integer
declare CloseMap in vmap.dll
declare integer CreateMap in vmap.dll string @
#define VMAP_GKEY "Global\vmapkey"
#define MAP_WRITE 1
#define MAP_READ 0
if CreateMap(VMAP_GKEY) >0
messagebox("创建内存文件失败")
endif
?ReadWriteMap(VMAP_GKEY ,ttoc(datetime()) ,MAP_WRITE)
clear dlls
在第二个VFP进程读取(声明语句和第一个同样)
?ReadWriteMap(VMAP_GKEY ,"",MAP_READ)
到此创建,测试vmap.dll的工作完成了。是不是很简单。通过vmap.dll ,Visual Foxpro就可以和其他应用
程序进行大量数据交换了 ,而不需要考虑DDE。