CreateFileMapping返回ERROR_INVALID_HANDLE

时间:2014-07-22 03:02:32

标签: c++ windows

我第一次尝试使用CreateFileMapping,当我使用GetLastError()时它会给我这个错误:

ERROR_INVALID_HANDLE: The handle is invalid.

这是我的代码:

    // create the name of our file-mapping object
    nTry++; // Ensures a unique string is used in case user closes and reopens
    wsprintfA(szName, FS6IPC_MSGNAME1 ":%X:%X", GetCurrentProcessId(), nTry);
    // stuff the name into a global atom
    m_atom = GlobalAddAtomA(szName);
    if (m_atom == 0)
   {    *pdwResult = ERR_ATOM;
        return FALSE;
    }

    // create the file-mapping object
    m_hMap = CreateFileMappingA(
                    (HANDLE)0xFFFFFFFF, // use system paging file
                    NULL,               // security
                    PAGE_READWRITE,     // protection
                    0, MAX_SIZE+256,       // size
                   szName);            // 

编辑:

第一个问题已经解决,但现在我的程序在其他地方崩溃了。

#define FS6IPC_MESSAGE_SUCCESS 1
#define FS6IPC_MESSAGE_FAILURE 0

// IPC message types
#define FS6IPC_READSTATEDATA_ID    1
#define FS6IPC_WRITESTATEDATA_ID   2

// read request structure
typedef struct tagFS6IPC_READSTATEDATA_HDR
{
  DWORD dwId;       // FS6IPC_READSTATEDATA_ID
  DWORD dwOffset;   // state table offset
  DWORD nBytes;     // number of bytes of state data to read
  void* pDest;      // destination buffer for data (client use only)
} FS6IPC_READSTATEDATA_HDR;

// write request structure
typedef struct tagFS6IPC_WRITESTATEDATA_HDR
{
  DWORD dwId;       // FS6IPC_WRITESTATEDATA_ID
  DWORD dwOffset;   // state table offset
  DWORD nBytes;     // number of bytes of state data to write
} FS6IPC_WRITESTATEDATA_HDR;

while (*pdw)
{   switch (*pdw)
    {   case FS6IPC_READSTATEDATA_ID:
            pHdrR = (FS6IPC_READSTATEDATA_HDR *) pdw;
            m_pNext += sizeof(FS6IPC_READSTATEDATA_HDR);
            if (pHdrR->pDest && pHdrR->nBytes)
                CopyMemory(pHdrR->pDest, m_pNext, pHdrR->nBytes);
            m_pNext += pHdrR->nBytes; // Debugger says the issue is here
            break;

        case FS6IPC_WRITESTATEDATA_ID:
            // This is a write, so there's no returned data to store
            pHdrW = (FS6IPC_WRITESTATEDATA_HDR *) pdw;
            m_pNext += sizeof(FS6IPC_WRITESTATEDATA_HDR) + pHdrW->nBytes;
            break;

        default:
            // Error! So terminate the scan
            *pdw = 0;
            break;
    }

    pdw = (DWORD *) m_pNext;
}

1 个答案:

答案 0 :(得分:4)

我猜你是在64位系统上运行,其中HANDLE是64位。操作系统非常正确 - 句柄值0x00000000FFFFFFFF是您的流程的无效句柄值。

你到底想要做什么?如果要创建由实际文件支持的文件映射,请传入该文件的句柄。如果要创建由页面文件支持的文件映射,请传入INVALID_HANDLE_VALUEINVALID_HANDLE_VALUE恰好是(HANDLE)-1,在32位系统上为0xFFFFFFFF,在64位系统上为0xFFFFFFFFFFFFFFFF,但这并不重要,因为您应该在任何情况下都只使用符号值INVALID_HANDLE_VALUE

如果你的应用程序在传递INVALID_HANDLE_VALUE时崩溃了,那不是因为对CreateFileMapping的调用失败,而是出于其他原因,你应该调试这一点。