//**************************************************************************************************
// COM-PORT OPERATIONS — OVERLAPPED:
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#include "Precompiled.h"
#include "SharedIncludes.h"
namespace XDeviceAccess {
//==================================================================================================

IntPtr ComPortHelpers::CreateOverlappedStructure()
{
   HANDLE hEvent = ::CreateEvent( NULL, TRUE, FALSE, NULL );
   if ( !hEvent )
      throw IntInteropExceptionCreator::CreateFromWin32Error();
   OVERLAPPED *pOverlapped;
   try { pOverlapped = (OVERLAPPED*)
      HUnsafeMemory::Allocate( sizeof( OVERLAPPED ) ); }
   catch (HOperationFailedException^ e) {
      ::CloseHandle( hEvent );
      throw IntInteropExceptionCreator::Create( e ); }
   pOverlapped->hEvent = hEvent;
   return (IntPtr)pOverlapped;
}

//--------------------------------------------------------------------------------------------------

void ComPortHelpers::ReleaseOverlappedStructure( [HOptional][HInterlockedAccess]
                                                 IntPtr% overlappedStructurePtr )
{
   auto pOverlapped = (OVERLAPPED*)($PVOID)
      HPointer::InterlockedNullValueExchange( overlappedStructurePtr );
   if ( !::CloseHandle( pOverlapped->hEvent ) )
      throw IntInteropExceptionCreator::CreateFromWin32Error();
   HUnsafeMemory::Free( pOverlapped );
}

//==================================================================================================
} // XDeviceAccess
