using NTwain.Data; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; namespace NTwain { /// /// Provides methods for managing memory on data exchanged with twain sources. /// This should only be used after the DSM has been opened. /// public class MemoryManager : IMemoryManager { /// /// Gets the singleton instance. /// public static readonly MemoryManager Instance = new MemoryManager(); private MemoryManager() { } /// /// Updates the entry point used by TWAIN. /// /// The entry point. internal void UpdateEntryPoint(TWEntryPoint entryPoint) { _twain2Entry = entryPoint; } TWEntryPoint _twain2Entry; /// /// Function to allocate memory. Calls to this must be coupled with later. /// /// The size in bytes. /// Handle to the allocated memory. public IntPtr Allocate(uint size) { IntPtr retVal = IntPtr.Zero; if (_twain2Entry != null && _twain2Entry.AllocateFunction != null) { retVal = _twain2Entry.AllocateFunction(size); } else { // 0x0040 is GPTR retVal = NativeMethods.WinGlobalAlloc(0x0040, new UIntPtr(size)); } if (retVal == IntPtr.Zero) { throw new OutOfMemoryException("Failed to allocate requested memory."); } return retVal; } /// /// Function to free memory. /// /// The handle from . public void Free(IntPtr handle) { if (_twain2Entry != null && _twain2Entry.FreeFunction != null) { _twain2Entry.FreeFunction(handle); } else { NativeMethods.WinGlobalFree(handle); } } /// /// Function to lock some memory. Calls to this must be coupled with later. /// /// The handle to allocated memory. /// Handle to the lock. public IntPtr Lock(IntPtr handle) { if (_twain2Entry != null && _twain2Entry.LockFunction != null) { return _twain2Entry.LockFunction(handle); } else { return NativeMethods.WinGlobalLock(handle); } } /// /// Function to unlock a previously locked memory region. /// /// The handle from . public void Unlock(IntPtr handle) { if (_twain2Entry != null && _twain2Entry.UnlockFunction != null) { _twain2Entry.UnlockFunction(handle); } else { NativeMethods.WinGlobalUnlock(handle); } } } }