mirror of
https://github.com/oliverbooth/VpSharp
synced 2024-11-22 19:38:47 +00:00
Reduce allocations in MarshalManagedToNative
This commit is contained in:
parent
0d0ce72cb2
commit
2d8dc52c3e
@ -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,13 +26,19 @@ 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);
|
|
||||||
return buffer;
|
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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public object MarshalNativeToManaged(nint pNativeData)
|
public object MarshalNativeToManaged(nint pNativeData)
|
||||||
|
Loading…
Reference in New Issue
Block a user