Skip to content

Commit

Permalink
Fix up string marshaller
Browse files Browse the repository at this point in the history
  • Loading branch information
ThadHouse committed Jan 28, 2024
1 parent 6e3f017 commit a458466
Showing 1 changed file with 12 additions and 4 deletions.
16 changes: 12 additions & 4 deletions src/ntcore/Natives/RefNetworkTableValueMarshaller.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.Marshalling;
Expand Down Expand Up @@ -79,9 +80,15 @@ public void FromManaged(in RefNetworkTableValue managed, Span<byte> 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<byte> 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;
Expand All @@ -92,7 +99,8 @@ public void FromManaged(in RefNetworkTableValue managed, Span<byte> 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<byte>(mem, len));
int exactLen = Encoding.UTF8.GetBytes(managed.m_stringSpan[i], new Span<byte>(mem, len));
Debug.Assert(exactLen == len);
strings[i] = new WpiStringMarshaller.WpiStringNative(mem, (nuint)len);
}

Expand Down

0 comments on commit a458466

Please sign in to comment.