From 1c25f8852975f3083c8a0aea3794eec98846ca40 Mon Sep 17 00:00:00 2001 From: David Hall Date: Fri, 7 Jun 2019 10:58:30 -0600 Subject: [PATCH] Added Write method to set string into memory --- Core/Extensions/StringHelper.cs | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/Core/Extensions/StringHelper.cs b/Core/Extensions/StringHelper.cs index 0314bbec..9b754c7e 100644 --- a/Core/Extensions/StringHelper.cs +++ b/Core/Extensions/StringHelper.cs @@ -1,6 +1,7 @@ using System; using System.Runtime.InteropServices; using System.Security; +using Vanara.InteropServices; namespace Vanara.Extensions { @@ -127,7 +128,7 @@ namespace Vanara.Extensions var ret = new byte[enc.GetByteCount(value) + (nullTerm ? chSz : 0)]; enc.GetBytes(value, 0, value.Length, ret, 0); if (nullTerm) - enc.GetBytes(new[] {'\0'}, 0, 1, ret, ret.Length - chSz); + enc.GetBytes(new[] { '\0' }, 0, 1, ret, ret.Length - chSz); return ret; } @@ -206,6 +207,28 @@ namespace Vanara.Extensions return s != null; } + /// Writes the specified string to a pointer to allocated memory. + /// The string value. + /// The pointer to the allocated memory. + /// The resulting number of bytes written. + /// if set to true include a null terminator at the end of the string in the count if does not equal null. + /// The character set of the string. + /// If known, the total number of bytes allocated to the native memory in . + public static void Write(string value, IntPtr ptr, out int byteCnt, bool nullTerm = true, CharSet charSet = CharSet.Auto, long allocatedBytes = long.MaxValue) + { + if (value is null) + { + byteCnt = 0; + return; + } + if (ptr == IntPtr.Zero) throw new ArgumentNullException(nameof(ptr)); + var bytes = GetBytes(value, nullTerm, charSet); + if (bytes.Length > allocatedBytes) + throw new ArgumentOutOfRangeException(nameof(allocatedBytes)); + byteCnt = bytes.Length; + Marshal.Copy(bytes, 0, ptr, byteCnt); + } + private static bool IsValue(IntPtr ptr) => ptr.ToInt64() >> 16 == 0; } } \ No newline at end of file