// SharedMemory.h: interface for the CSharedMemory class.
//
//////////////////////////////////////////////////////////////////////

#pragma once
#include <afx.h>

#include "DllDefines.h"

class UTILITYDLL CSharedMemory : public CObject
{
public:
    CSharedMemory();
    CSharedMemory(LPCTSTR pszName, DWORD dwBytes, bool NameExtension);
    ~CSharedMemory() final;

    DWORD_PTR CreateSharedMem(LPCTSTR pszName, DWORD dwBytes);
    DWORD_PTR CreateSharedMemEx(LPCTSTR pszName, DWORD dwBytes, bool NameExtension = false);
    LPVOID    getDirectMap() const;

    DWORD GetSize() const;
    //
    // methods to set whether to ummap shm upon destruction
    void SetUnmappedOnDeleted(bool bDelete);

    // Will return 0 or ERROR_ALREADY_EXISTS if it already exists.
    LPVOID Open(DWORD dwTimeout = INFINITE); // SM must be opened before use. The pointer
                                             // returns must be type casted to it type
                                             // Returns NULL if the SM was not created ot failed
    bool Close();                            // SM should be closed after use so that others can open the SM
    bool IsOpen() const
    {
        return m_bOpen;
    } // Check if SM is opened

    DWORD GetLength() const
    {
        return m_dwLength;
    }

#ifdef _DEBUG
    virtual void AssertValid() const;
    virtual void Dump(CDumpContext& dc) const;
#endif

protected:
    DECLARE_DYNAMIC(CSharedMemory)

private:
    DWORD CalculateShmSize(DWORD dwSize) const;

    HANDLE m_hMutex{ nullptr };
    LPVOID m_pvData{ nullptr };
    HANDLE m_hMapping{ nullptr };
    bool   m_bOpen{ false };
    DWORD  m_dwLength{ 0 };
    bool   m_bUnMappedOnDeleted{ true };
};
