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)
{
if (_twain2Entry != null && _twain2Entry.AllocateFunction != null)
{
return _twain2Entry.AllocateFunction(size);
}
else
{
// 0x0040 is GPTR
return WinGlobalAlloc(0x0040, new UIntPtr(size));
}
}
///
/// Function to free memory.
///
/// The handle from .
public void Free(IntPtr handle)
{
if (_twain2Entry != null && _twain2Entry.FreeFunction != null)
{
_twain2Entry.FreeFunction(handle);
}
else
{
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 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
{
WinGlobalUnlock(handle);
}
}
#region old mem stuff for twain 1.x
[DllImport("kernel32", SetLastError = true, EntryPoint = "GlobalAlloc")]
static extern IntPtr WinGlobalAlloc(uint uFlags, UIntPtr dwBytes);
[DllImport("kernel32", SetLastError = true, EntryPoint = "GlobalFree")]
static extern IntPtr WinGlobalFree(IntPtr hMem);
[DllImport("kernel32", SetLastError = true, EntryPoint = "GlobalLock")]
static extern IntPtr WinGlobalLock(IntPtr handle);
[DllImport("kernel32", SetLastError = true, EntryPoint = "GlobalUnlock")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool WinGlobalUnlock(IntPtr handle);
#endregion
}
}