diff --git a/src/ntcore/Natives/RefNetworkTableValueMarshaller.cs b/src/ntcore/Natives/RefNetworkTableValueMarshaller.cs index c36c1f3c..a5de05aa 100644 --- a/src/ntcore/Natives/RefNetworkTableValueMarshaller.cs +++ b/src/ntcore/Natives/RefNetworkTableValueMarshaller.cs @@ -1,4 +1,5 @@ using System; +using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.InteropServices.Marshalling; @@ -79,9 +80,15 @@ public void FromManaged(in RefNetworkTableValue managed, Span callerAlloca m_doAssignment = true; break; case NetworkTableType.String: - byte[] stringArrayData = Encoding.UTF8.GetBytes(managed.m_stringValue!); - m_toPin = MemoryMarshal.AsBytes(stringArrayData.AsSpan()).GetPinnableReference(); - m_nativeValue.data.valueString = new(null, (nuint)stringArrayData.Length); + int byteCount = Encoding.UTF8.GetByteCount(managed.m_stringValue!); + Span stringSpan = callerAllocatedBuffer; + if (byteCount > stringSpan.Length) { + stringSpan = new byte[byteCount]; + } + int exactBytes = Encoding.UTF8.GetBytes(managed.m_stringValue!, stringSpan); + Debug.Assert(exactBytes == byteCount); + m_toPin = stringSpan.GetPinnableReference(); + m_nativeValue.data.valueString = new(null, (nuint)stringSpan.Length); m_toAssignPin = m_nativeValue.data.valueString.Str; m_doAssignment = true; break; @@ -92,7 +99,8 @@ public void FromManaged(in RefNetworkTableValue managed, Span callerAlloca { int len = Encoding.UTF8.GetByteCount(managed.m_stringSpan[i]); byte* mem = (byte*)NativeMemory.Alloc((nuint)len); - Encoding.UTF8.GetBytes(managed.m_stringSpan[i], new Span(mem, len)); + int exactLen = Encoding.UTF8.GetBytes(managed.m_stringSpan[i], new Span(mem, len)); + Debug.Assert(exactLen == len); strings[i] = new WpiStringMarshaller.WpiStringNative(mem, (nuint)len); }