MapViewOfFileEx 失败的问题

fxj51983 2007-11-26 08:18:26
代码见下
#define MAX_SHM_BUF_LEN 4 * 1024
DWORD dwErr = 0;
HANDLE hMapFile = NULL;
void *pBaseMapFile = NULL;

hMapFile = CreateFileMapping( (HANDLE)0xFFFFFFFF,
NULL,
PAGE_READWRITE,
0,
MAX_SHM_BUF_LEN,
"DHOME_DB");


pBaseMapFile = MapViewOfFileEx(hMapFile,
FILE_MAP_READ|FILE_MAP_WRITE,
0,
MAX_SHM_BUF_LEN,
0,
0x00bb0000);

dwErr = GetLastError();

return pBaseMapFile;
dwErr 为1132,说什么指定的基址或文件偏移量没有适当对齐。
...全文
528 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
xalangying 2007-11-30
  • 打赏
  • 举报
回复
请看MSDN中MapViewOfFile函数第四个参数的说明
dwFileOffsetLow
[in] A low-order DWORD of the file offset where the view is to begin. The combination of the high and low offsets must specify an offset within the file that matches the memory allocation granularity of the system, or the function fails. That is, the offset must be a multiple of the allocation granularity. To obtain the memory allocation granularity of the system, use the GetSystemInfo function, which fills in the members of a SYSTEM_INFO structure.

也就是说dwFileOffsetHigh和dwFileOffsetLow组成偏移地址值而且必须是操作系统的分配粒度的整数倍,对于Windows操作系统,分配粒度固定为64KB。可以通过如下代码来动态获取当前操作系统的分配粒度:
SYSTEM_INFO sinf;
GetSystemInfo(&sinf);
DWORD dwAllocationGranularity = sinf.dwAllocationGranularity;
代码可以写成以下的方式

#define     MAX_SHM_BUF_LEN       4   *   1024 
DWORD dwErr = 0;
HANDLE hMapFile = NULL;
void *pBaseMapFile = NULL;

hMapFile = CreateFileMapping( (HANDLE)0xFFFFFFFF,
NULL,
PAGE_READWRITE,
0,
MAX_SHM_BUF_LEN,
"DHOME_DB");


SYSTEM_INFO sinf;
GetSystemInfo(&sinf);
DWORD dwAllocationGranularity = sinf.dwAllocationGranularity;
DWORD size = (MAX_SHM_BUF_LEN/dwAllocationGranularity+1)*dwAllocationGranularity;
pBaseMapFile = MapViewOfFileEx(hMapFile,
FILE_MAP_READ ¦FILE_MAP_WRITE,
0,
size ,
0,
0x00bb0000);

dwErr = GetLastError();

return pBaseMapFile;
飞哥 2007-11-27
  • 打赏
  • 举报
回复
这是我写的:)


m_hMapObject = CreateFileMapping((HANDLE)0xFFFFFFFF, //(无效句柄)表明与文件无关
NULL, //安全权限
PAGE_READWRITE,//读写权限
0,//最小值
0x1000,//最大值
_TEXT("MySharedMemory"));//映射名称

if(!m_hMapObject)
{
// AfxMessageBox("不能创建共享内存");
return FALSE;
}

m_pszMapView = (LPSTR)MapViewOfFile(m_hMapObject,//内存映射的句柄
FILE_MAP_WRITE,//权限
0, 0, 0);

if(!m_pszMapView)
{
// AfxMessageBox("不能映射共享内存");
return FALSE;
}

jixingzhong 2007-11-27
  • 打赏
  • 举报
回复
。。。
fxj51983 2007-11-27
  • 打赏
  • 举报
回复

pBaseMapFile = MapViewOfFileEx(hMapFile,
FILE_MAP_READ ¦FILE_MAP_WRITE,
0,
0,
0,
0x00bb0000);

这样就可以了,呵呵

69,369

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧