1

Say I want to a generated a wrapper function to CreateFile function

This new function will not generate a real file on the disk but create file mapping object and return a handle to the new object.

I've looked at this example, Creating Named Shared Memory, and tried to implement my function:

#define BUF_SIZE 256
TCHAR szName[] = TEXT("Global\\MyFileMappingObject");

HANDLE MyCreateFile()
{
     HANDLE hMapFile = CreateFileMapping(
        INVALID_HANDLE_VALUE,    // use paging file
        NULL,                    // default security
        PAGE_READWRITE,          // read/write access
        0,                       // maximum object size (high-order DWORD)
        BUF_SIZE,                // maximum object size (low-order DWORD)
        szName);                 // name of mapping object

     return hMapFile;
}

Problem

This looked OK to me, however, when tried using the returned HANDLE in ReadFile function I got error code 6 The handle is invalid.

Question

Can file mapping object and file object be used interchangeably? If so, then what is the issue with my code? If not, any idea how can such function be implemented?

idanshmu
  • 5,061
  • 6
  • 46
  • 92
  • Why would you use `ReadFile` on a named memory region? It's supposed to be used with `MapViewOfFile`. –  Mar 19 '15 at 12:13
  • The `ReadFile` is just an example of using the returned `HANDLE` of `MyCreateFile`. It is here to show that the implementation of `MyCreateFile` is faulty and I'm trying to understand why. – idanshmu Mar 19 '15 at 12:16

1 Answers1

0

The handle that CreateFileMapping returns is a file mapping object and not that of regular files. CreateFileMapping is part of a family of functions which allows access to files as if they are memory or array of bytes. One way, would be to also call MapViewOfFile(with appropriate parameters) inside your MyCreateFile() function and let MyCreateFile() function return the pointer which is returned by MapViewOfFile. Now you can write your MyReadFile() and MyWriteFile() using this pointer.

It would be more nice if you can create a class and include all these functions inside it.

class CustomFile
{
    private:
            LPVOID *m_pData;
    public:                
            //m_pData is initialized here via CreateFileMapping and   
            //MapViewOfFile.
            CreateFile(...);   

            //m_pData is used here.
            ReadFile(...);
            WriteFile(...);
};
sameerkn
  • 2,209
  • 1
  • 12
  • 13