Reduce allocations in MarshalManagedToNative

This commit is contained in:
Oliver Booth 2022-11-30 00:46:18 +00:00
parent 0d0ce72cb2
commit 2d8dc52c3e
No known key found for this signature in database
GPG Key ID: 32A00B35503AF634
1 changed files with 13 additions and 7 deletions

View File

@ -1,4 +1,4 @@
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Text; using System.Text;
namespace VpSharp.Internal; namespace VpSharp.Internal;
@ -26,14 +26,20 @@ internal sealed class Utf8StringToNative : ICustomMarshaler
return -1; return -1;
} }
public nint MarshalManagedToNative(object managedObj) public unsafe nint MarshalManagedToNative(object managedObj)
{ {
byte[] utf8Data = Encoding.UTF8.GetBytes((string)managedObj); var managedString = (string)managedObj;
nint buffer = Marshal.AllocHGlobal(utf8Data.Length + 1); Span<byte> utf8Bytes = stackalloc byte[managedString.Length];
Marshal.Copy(utf8Data, 0, buffer, utf8Data.Length); Encoding.UTF8.GetBytes(managedString, utf8Bytes);
Marshal.WriteByte(buffer, utf8Data.Length, 0);
fixed (byte* data = &MemoryMarshal.GetReference(utf8Bytes))
{
IntPtr buffer = Marshal.AllocHGlobal(utf8Bytes.Length + 1);
Buffer.MemoryCopy(data, (void*)buffer, utf8Bytes.Length, utf8Bytes.Length);
Marshal.WriteByte(buffer, utf8Bytes.Length, 0);
return buffer; return buffer;
} }
}
public object MarshalNativeToManaged(nint pNativeData) public object MarshalNativeToManaged(nint pNativeData)
{ {