Added ISimpleMemoryMethods (subset of IMemoryMethods with just alloc and free) and MemoryMethodsFromSimple<TSimple> which implements most of IMemoryMethods using just the methods from ISimpleMemoryMethods.

pull/119/head
dahall 2020-04-07 14:34:28 -06:00
parent cd46adfb6b
commit a59b4bfba7
1 changed files with 139 additions and 64 deletions

View File

@ -16,16 +16,17 @@ namespace Vanara.InteropServices
{
/// <summary>Each string is separated by a single '\0' character and is terminated by two '\0' characters.</summary>
Concatenated,
/// <summary>A contiguous block of memory containing an array of pointers to strings followed by a NULL pointer and then followed by the actual strings.</summary>
/// <summary>
/// A contiguous block of memory containing an array of pointers to strings followed by a NULL pointer and then followed by the
/// actual strings.
/// </summary>
Packed
}
/// <summary>Interface to capture unmanaged memory methods.</summary>
public interface IMemoryMethods
public interface IMemoryMethods : ISimpleMemoryMethods
{
/// <summary>Gets the allocation method.</summary>
Func<int, IntPtr> AllocMem { get; }
/// <summary>Gets the Ansi <see cref="SecureString"/> allocation method.</summary>
Func<SecureString, IntPtr> AllocSecureStringAnsi { get; }
@ -38,9 +39,6 @@ namespace Vanara.InteropServices
/// <summary>Gets the Unicode string allocation method.</summary>
Func<string, IntPtr> AllocStringUni { get; }
/// <summary>Gets the free method.</summary>
Action<IntPtr> FreeMem { get; }
/// <summary>Gets the Ansi <see cref="SecureString"/> free method.</summary>
Action<IntPtr> FreeSecureStringAnsi { get; }
@ -62,8 +60,9 @@ namespace Vanara.InteropServices
SizeT Size { get; set; }
/// <summary>
/// Adds reference to other SafeMemoryHandle objects, the pointer to which are referred to by this object. This is to ensure that such objects being
/// referred to wouldn't be unreferenced until this object is active. For e.g. when this object is an array of pointers to other objects
/// Adds reference to other SafeMemoryHandle objects, the pointer to which are referred to by this object. This is to ensure that
/// such objects being referred to wouldn't be unreferenced until this object is active. For e.g. when this object is an array of
/// pointers to other objects
/// </summary>
/// <param name="children">Collection of SafeMemoryHandle objects referred to by this object.</param>
void AddSubReference(IEnumerable<ISafeMemoryHandle> children);
@ -73,8 +72,8 @@ namespace Vanara.InteropServices
IntPtr DangerousGetHandle();
/// <summary>
/// Extracts an array of structures of <typeparamref name="T"/> containing <paramref name="count"/> items. <note type="note">This call can cause memory
/// exceptions if the pointer does not have sufficient allocated memory to retrieve all the structures.</note>
/// Extracts an array of structures of <typeparamref name="T"/> containing <paramref name="count"/> items. <note type="note">This
/// call can cause memory exceptions if the pointer does not have sufficient allocated memory to retrieve all the structures.</note>
/// </summary>
/// <typeparam name="T">The type of the structures to retrieve.</typeparam>
/// <param name="count">The number of structures to retrieve.</param>
@ -83,8 +82,8 @@ namespace Vanara.InteropServices
T[] ToArray<T>(int count, int prefixBytes = 0);
/// <summary>
/// Extracts an enumeration of structures of <typeparamref name="T"/> containing <paramref name="count"/> items. <note type="note">This call can cause
/// memory exceptions if the pointer does not have sufficient allocated memory to retrieve all the structures.</note>
/// Extracts an enumeration of structures of <typeparamref name="T"/> containing <paramref name="count"/> items. <note
/// type="note">This call can cause memory exceptions if the pointer does not have sufficient allocated memory to retrieve all the structures.</note>
/// </summary>
/// <typeparam name="T">The type of the structures to retrieve.</typeparam>
/// <param name="count">The number of structures to retrieve.</param>
@ -106,28 +105,80 @@ namespace Vanara.InteropServices
string ToString(int len, int prefixBytes, CharSet charSet = CharSet.Unicode);
/// <summary>
/// Gets an enumerated list of strings from a block of unmanaged memory where each string is separated by a single '\0' character and is terminated by
/// two '\0' characters.
/// Gets an enumerated list of strings from a block of unmanaged memory where each string is separated by a single '\0' character
/// and is terminated by two '\0' characters.
/// </summary>
/// <param name="charSet">The character set of the strings.</param>
/// <param name="prefixBytes">Number of bytes preceding the array of string pointers.</param>
/// <returns>Enumeration of strings.</returns>
IEnumerable<string> ToStringEnum(CharSet charSet = CharSet.Auto, int prefixBytes = 0);
/// <summary>Returns an enumeration of strings from memory where each string is pointed to by a preceding list of pointers of length <paramref name="count"/>.</summary>
/// <summary>
/// Returns an enumeration of strings from memory where each string is pointed to by a preceding list of pointers of length
/// <paramref name="count"/>.
/// </summary>
/// <param name="count">The count.</param>
/// <param name="charSet">The character set of the strings.</param>
/// <param name="prefixBytes">Number of bytes preceding the array of string pointers.</param>
/// <returns>An enumerated list of strings.</returns>
IEnumerable<string> ToStringEnum(int count, CharSet charSet = CharSet.Auto, int prefixBytes = 0);
/// <summary>Marshals data from this block of memory to a newly allocated managed object of the type specified by a generic type parameter.</summary>
/// <summary>
/// Marshals data from this block of memory to a newly allocated managed object of the type specified by a generic type parameter.
/// </summary>
/// <typeparam name="T">The type of the object to which the data is to be copied. This must be a structure.</typeparam>
/// <param name="prefixBytes">Number of bytes preceding the structure.</param>
/// <returns>A managed object that contains the data that this <see cref="SafeMemoryHandleExt{T}"/> holds.</returns>
T ToStructure<T>(int prefixBytes = 0);
}
/// <summary>Interface to capture unmanaged simple (alloc/free) memory methods.</summary>
public interface ISimpleMemoryMethods
{
/// <summary>Gets the allocation method.</summary>
Func<int, IntPtr> AllocMem { get; }
/// <summary>Gets the free method.</summary>
Action<IntPtr> FreeMem { get; }
}
/// <summary>Implementation of <see cref="IMemoryMethods"/> using just the methods from <see cref="ISimpleMemoryMethods"/>.</summary>
/// <typeparam name="TSimple">The type of the simple.</typeparam>
/// <seealso cref="Vanara.InteropServices.IMemoryMethods"/>
public class MemoryMethodsFromSimple<TSimple> : IMemoryMethods where TSimple : ISimpleMemoryMethods, new()
{
/// <summary>A static instance of TSimple.</summary>
public static TSimple SimpleInstance = new TSimple();
/// <summary>Gets the Ansi <see cref="SecureString"/> allocation method.</summary>
public Func<SecureString, IntPtr> AllocSecureStringAnsi => s => StringHelper.AllocSecureString(s, CharSet.Ansi, AllocMem);
/// <summary>Gets the Unicode <see cref="SecureString"/> allocation method.</summary>
public Func<SecureString, IntPtr> AllocSecureStringUni => s => StringHelper.AllocSecureString(s, CharSet.Unicode, AllocMem);
/// <summary>Gets the Ansi string allocation method.</summary>
public Func<string, IntPtr> AllocStringAnsi => s => StringHelper.AllocString(s, CharSet.Ansi, AllocMem);
/// <summary>Gets the Unicode string allocation method.</summary>
public Func<string, IntPtr> AllocStringUni => s => StringHelper.AllocString(s, CharSet.Unicode, AllocMem);
/// <summary>Gets the Ansi <see cref="SecureString"/> free method.</summary>
public Action<IntPtr> FreeSecureStringAnsi => FreeMem;
/// <summary>Gets the Unicode <see cref="SecureString"/> free method.</summary>
public Action<IntPtr> FreeSecureStringUni => FreeMem;
/// <summary>Gets the reallocation method.</summary>
/// <exception cref="System.NotImplementedException"></exception>
public Func<IntPtr, int, IntPtr> ReAllocMem => throw new NotImplementedException();
/// <summary>Gets the allocation method.</summary>
public Func<int, IntPtr> AllocMem => SimpleInstance.AllocMem;
/// <summary>Gets the free method.</summary>
public Action<IntPtr> FreeMem => SimpleInstance.FreeMem;
}
/// <summary>Abstract base class for all SafeHandle derivatives that encapsulate handling unmanaged memory.</summary>
/// <seealso cref="System.Runtime.InteropServices.SafeHandle"/>
public abstract class SafeAllocatedMemoryHandle : SafeHandle
@ -137,16 +188,32 @@ namespace Vanara.InteropServices
/// <param name="ownsHandle">if set to <c>true</c> if this class is responsible for freeing the memory on disposal.</param>
protected SafeAllocatedMemoryHandle(IntPtr handle, bool ownsHandle) : base(IntPtr.Zero, ownsHandle) => SetHandle(handle);
/// <summary>Dumps memory to byte string.</summary>
[ExcludeFromCodeCoverage]
public string Dump => Size == 0 ? "" : string.Join(" ", GetBytes(0, Size).Select(b => b.ToString("X2")).ToArray());
/// <summary>Gets or sets the size in bytes of the allocated memory block.</summary>
/// <value>The size in bytes of the allocated memory block.</value>
public abstract SizeT Size { get; set; }
#if DEBUG
/// <summary>Dumps memory to byte string.</summary>
[ExcludeFromCodeCoverage]
public string Dump => Size == 0 ? "" : string.Join(" ", GetBytes(0, Size).Select(b => b.ToString("X2")).ToArray());
#endif
/// <summary>Performs an explicit conversion from <see cref="SafeAllocatedMemoryHandle"/> to <see cref="byte"/> pointer.</summary>
/// <param name="hMem">The <see cref="SafeAllocatedMemoryHandle"/> instance.</param>
/// <returns>The result of the conversion.</returns>
public static unsafe explicit operator byte*(SafeAllocatedMemoryHandle hMem) => (byte*)hMem.handle;
/// <summary>Performs an explicit conversion from <see cref="SafeAllocatedMemoryHandle"/> to <see cref="SafeBuffer"/>.</summary>
/// <param name="hMem">The <see cref="SafeAllocatedMemoryHandle"/> instance.</param>
/// <returns>The result of the conversion.</returns>
public static explicit operator SafeBuffer(SafeAllocatedMemoryHandle hMem) => new SafeBufferImpl(hMem);
/// <summary>Performs an implicit conversion from <see cref="SafeAllocatedMemoryHandle"/> to <see cref="System.IntPtr"/>.</summary>
/// <param name="hMem">The <see cref="SafeAllocatedMemoryHandle"/> instance.</param>
/// <returns>The result of the conversion.</returns>
public static implicit operator IntPtr(SafeAllocatedMemoryHandle hMem) => hMem.handle;
/// <summary>Fills the allocated memory with a specific byte value.</summary>
/// <param name="value">The byte value.</param>
public virtual void Fill(byte value) => Fill(value, Size);
@ -186,21 +253,6 @@ namespace Vanara.InteropServices
return ret;
}
/// <summary>Performs an explicit conversion from <see cref="SafeAllocatedMemoryHandle"/> to <see cref="SafeBuffer"/>.</summary>
/// <param name="hMem">The <see cref="SafeAllocatedMemoryHandle"/> instance.</param>
/// <returns>The result of the conversion.</returns>
public static explicit operator SafeBuffer(SafeAllocatedMemoryHandle hMem) => new SafeBufferImpl(hMem);
/// <summary>Performs an explicit conversion from <see cref="SafeAllocatedMemoryHandle"/> to <see cref="byte"/> pointer.</summary>
/// <param name="hMem">The <see cref="SafeAllocatedMemoryHandle"/> instance.</param>
/// <returns>The result of the conversion.</returns>
public static unsafe explicit operator byte*(SafeAllocatedMemoryHandle hMem) => (byte*)hMem.handle;
/// <summary>Performs an implicit conversion from <see cref="SafeAllocatedMemoryHandle"/> to <see cref="System.IntPtr"/>.</summary>
/// <param name="hMem">The <see cref="SafeAllocatedMemoryHandle"/> instance.</param>
/// <returns>The result of the conversion.</returns>
public static implicit operator IntPtr(SafeAllocatedMemoryHandle hMem) => hMem.handle;
private class SafeBufferImpl : SafeBuffer
{
public SafeBufferImpl(SafeAllocatedMemoryHandle hMem) : base(false) => Initialize((ulong)hMem.Size);
@ -235,7 +287,10 @@ namespace Vanara.InteropServices
/// <param name="ownsHandle">if set to <c>true</c> if this class is responsible for freeing the memory on disposal.</param>
protected SafeMemoryHandle(IntPtr handle, SizeT size, bool ownsHandle) : base(handle, ownsHandle) => sz = size;
/// <summary>Allocates from unmanaged memory to represent an array of pointers and marshals the unmanaged pointers (IntPtr) to the native array equivalent.</summary>
/// <summary>
/// Allocates from unmanaged memory to represent an array of pointers and marshals the unmanaged pointers (IntPtr) to the native
/// array equivalent.
/// </summary>
/// <param name="bytes">Array of unmanaged pointers</param>
/// <returns>SafeHGlobalHandle object to an native (unmanaged) array of pointers</returns>
protected SafeMemoryHandle(byte[] bytes) : base(IntPtr.Zero, true)
@ -284,8 +339,8 @@ namespace Vanara.InteropServices
/// <summary>When overridden in a derived class, executes the code required to free the handle.</summary>
/// <returns>
/// true if the handle is released successfully; otherwise, in the event of a catastrophic failure, false. In this case, it generates a
/// releaseHandleFailed MDA Managed Debugging Assistant.
/// true if the handle is released successfully; otherwise, in the event of a catastrophic failure, false. In this case, it
/// generates a releaseHandleFailed MDA Managed Debugging Assistant.
/// </returns>
protected override bool ReleaseHandle()
{
@ -307,8 +362,8 @@ namespace Vanara.InteropServices
public abstract class SafeMemoryHandleExt<TMem> : SafeMemoryHandle<TMem>, ISafeMemoryHandle where TMem : IMemoryMethods, new()
{
/// <summary>
/// Maintains reference to other SafeMemoryHandleExt objects, the pointer to which are referred to by this object. This is to ensure that such objects
/// being referred to wouldn't be unreferenced until this object is active.
/// Maintains reference to other SafeMemoryHandleExt objects, the pointer to which are referred to by this object. This is to ensure
/// that such objects being referred to wouldn't be unreferenced until this object is active.
/// </summary>
private List<ISafeMemoryHandle> references;
@ -323,12 +378,18 @@ namespace Vanara.InteropServices
/// <param name="ownsHandle">if set to <c>true</c> if this class is responsible for freeing the memory on disposal.</param>
protected SafeMemoryHandleExt(IntPtr handle, SizeT size, bool ownsHandle) : base(handle, size, ownsHandle) { }
/// <summary>Allocates from unmanaged memory to represent an array of pointers and marshals the unmanaged pointers (IntPtr) to the native array equivalent.</summary>
/// <summary>
/// Allocates from unmanaged memory to represent an array of pointers and marshals the unmanaged pointers (IntPtr) to the native
/// array equivalent.
/// </summary>
/// <param name="bytes">Array of unmanaged pointers</param>
/// <returns>SafeHGlobalHandle object to an native (unmanaged) array of pointers</returns>
protected SafeMemoryHandleExt(byte[] bytes) : base(bytes) { }
/// <summary>Allocates from unmanaged memory to represent an array of pointers and marshals the unmanaged pointers (IntPtr) to the native array equivalent.</summary>
/// <summary>
/// Allocates from unmanaged memory to represent an array of pointers and marshals the unmanaged pointers (IntPtr) to the native
/// array equivalent.
/// </summary>
/// <param name="values">Array of unmanaged pointers</param>
/// <returns>SafeMemoryHandleExt object to an native (unmanaged) array of pointers</returns>
protected SafeMemoryHandleExt(IntPtr[] values) : this(IntPtr.Size * values.Length) => Marshal.Copy(values, 0, handle, values.Length);
@ -344,8 +405,9 @@ namespace Vanara.InteropServices
}
/// <summary>
/// Adds reference to other SafeMemoryHandle objects, the pointer to which are referred to by this object. This is to ensure that such objects being
/// referred to wouldn't be unreferenced until this object is active. For e.g. when this object is an array of pointers to other objects
/// Adds reference to other SafeMemoryHandle objects, the pointer to which are referred to by this object. This is to ensure that
/// such objects being referred to wouldn't be unreferenced until this object is active. For e.g. when this object is an array of
/// pointers to other objects
/// </summary>
/// <param name="children">Collection of SafeMemoryHandle objects referred to by this object.</param>
public void AddSubReference(IEnumerable<ISafeMemoryHandle> children)
@ -355,8 +417,9 @@ namespace Vanara.InteropServices
references.AddRange(children);
}
/// <summary>Extracts an array of structures of <typeparamref name="T"/> containing <paramref name="count"/> items.
/// <note type="note">This call can cause memory exceptions if the pointer does not have sufficient allocated memory to retrieve all the structures.</note>
/// <summary>
/// Extracts an array of structures of <typeparamref name="T"/> containing <paramref name="count"/> items. <note type="note">This
/// call can cause memory exceptions if the pointer does not have sufficient allocated memory to retrieve all the structures.</note>
/// </summary>
/// <typeparam name="T">The type of the structures to retrieve.</typeparam>
/// <param name="count">The number of structures to retrieve.</param>
@ -372,8 +435,9 @@ namespace Vanara.InteropServices
return handle.ToArray<T>(count, prefixBytes, sz);
}
/// <summary>Extracts an enumeration of structures of <typeparamref name="T"/> containing <paramref name="count"/> items.
/// <note type="note">This call can cause memory exceptions if the pointer does not have sufficient allocated memory to retrieve all the structures.</note>
/// <summary>
/// Extracts an enumeration of structures of <typeparamref name="T"/> containing <paramref name="count"/> items. <note
/// type="note">This call can cause memory exceptions if the pointer does not have sufficient allocated memory to retrieve all the structures.</note>
/// </summary>
/// <typeparam name="T">The type of the structures to retrieve.</typeparam>
/// <param name="count">The number of structures to retrieve.</param>
@ -406,7 +470,10 @@ namespace Vanara.InteropServices
return len == -1 ? str : str.Substring(0, len);
}
/// <summary>Returns an enumeration of strings from memory where each string is pointed to by a preceding list of pointers of length <paramref name="count"/>.</summary>
/// <summary>
/// Returns an enumeration of strings from memory where each string is pointed to by a preceding list of pointers of length
/// <paramref name="count"/>.
/// </summary>
/// <param name="count">The count of expected strings.</param>
/// <param name="charSet">The character set of the strings.</param>
/// <param name="prefixBytes">Number of bytes preceding the array of string pointers.</param>
@ -414,15 +481,17 @@ namespace Vanara.InteropServices
public IEnumerable<string> ToStringEnum(int count, CharSet charSet = CharSet.Auto, int prefixBytes = 0) => IsInvalid ? new string[0] : handle.ToStringEnum(count, charSet, prefixBytes, sz);
/// <summary>
/// Gets an enumerated list of strings from a block of unmanaged memory where each string is separated by a single '\0' character and is terminated by
/// two '\0' characters.
/// Gets an enumerated list of strings from a block of unmanaged memory where each string is separated by a single '\0' character
/// and is terminated by two '\0' characters.
/// </summary>
/// <param name="charSet">The character set of the strings.</param>
/// <param name="prefixBytes">Number of bytes preceding the array of string pointers.</param>
/// <returns>An enumerated list of strings.</returns>
public IEnumerable<string> ToStringEnum(CharSet charSet = CharSet.Auto, int prefixBytes = 0) => IsInvalid ? new string[0] : handle.ToStringEnum(charSet, prefixBytes, sz);
/// <summary>Marshals data from this block of memory to a newly allocated managed object of the type specified by a generic type parameter.</summary>
/// <summary>
/// Marshals data from this block of memory to a newly allocated managed object of the type specified by a generic type parameter.
/// </summary>
/// <typeparam name="T">The type of the object to which the data is to be copied. This must be a structure.</typeparam>
/// <param name="prefixBytes">Number of bytes preceding the structure.</param>
/// <returns>A managed object that contains the data that this <see cref="SafeMemoryHandleExt{T}"/> holds.</returns>
@ -432,14 +501,16 @@ namespace Vanara.InteropServices
return handle.ToStructure<T>(sz, prefixBytes);
}
/// <summary>
/// Marshals data from a managed list of specified type to an offset within this allocated memory.
/// </summary>
/// <typeparam name="T">A type of the enumerated managed object that holds the data to be marshaled. The object must be a structure or an instance of a
/// formatted class.</typeparam>
/// <summary>Marshals data from a managed list of specified type to an offset within this allocated memory.</summary>
/// <typeparam name="T">
/// A type of the enumerated managed object that holds the data to be marshaled. The object must be a structure or an instance of a
/// formatted class.
/// </typeparam>
/// <param name="items">The enumerated list of items to marshal.</param>
/// <param name="autoExtend">if set to <c>true</c> automatically extend the allocated memory to the size required to hold <paramref name="items"/>.</param>
/// <param name="offset">The number of bytes to skip before writing the first element of <paramref name="items" />.</param>
/// <param name="autoExtend">
/// if set to <c>true</c> automatically extend the allocated memory to the size required to hold <paramref name="items"/>.
/// </param>
/// <param name="offset">The number of bytes to skip before writing the first element of <paramref name="items"/>.</param>
public void Write<T>(IEnumerable<T> items, bool autoExtend = true, int offset = 0)
{
if (IsInvalid) throw new MemberAccessException("Safe memory pointer is not valid.");
@ -458,7 +529,9 @@ namespace Vanara.InteropServices
/// <summary>Writes the specified value to an offset within this allocated memory.</summary>
/// <typeparam name="T">The type of the value to write.</typeparam>
/// <param name="value">The value to write.</param>
/// <param name="autoExtend">if set to <c>true</c> automatically extend the allocated memory to the size required to hold <paramref name="value"/>.</param>
/// <param name="autoExtend">
/// if set to <c>true</c> automatically extend the allocated memory to the size required to hold <paramref name="value"/>.
/// </param>
/// <param name="offset">The number of bytes to offset from the beginning of this allocated memory before writing.</param>
public void Write<T>(in T value, bool autoExtend = true, int offset = 0) where T : struct
{
@ -475,7 +548,9 @@ namespace Vanara.InteropServices
/// <summary>Writes the specified value to an offset within this allocated memory.</summary>
/// <param name="value">The value to write.</param>
/// <param name="autoExtend">if set to <c>true</c> automatically extend the allocated memory to the size required to hold <paramref name="value"/>.</param>
/// <param name="autoExtend">
/// if set to <c>true</c> automatically extend the allocated memory to the size required to hold <paramref name="value"/>.
/// </param>
/// <param name="offset">The number of bytes to offset from the beginning of this allocated memory before writing.</param>
public void Write(object value, bool autoExtend = true, int offset = 0)
{
@ -493,8 +568,8 @@ namespace Vanara.InteropServices
/// <summary>When overridden in a derived class, executes the code required to free the handle.</summary>
/// <returns>
/// true if the handle is released successfully; otherwise, in the event of a catastrophic failure, false. In this case, it generates a
/// releaseHandleFailed MDA Managed Debugging Assistant.
/// true if the handle is released successfully; otherwise, in the event of a catastrophic failure, false. In this case, it
/// generates a releaseHandleFailed MDA Managed Debugging Assistant.
/// </returns>
protected override bool ReleaseHandle()
{