Come azzerare la memoria allocata da Marshal.AllocHGlobal?
-
18-09-2019 - |
Domanda
Io sono l'allocazione della memoria non gestita nella mia applicazione via Marshal.AllocHGlobal
. Sto quindi copiare un insieme di byte da questa posizione e convertire il segmento risultante di memoria a un struct
prima di liberare nuovamente la memoria tramite Marshal.FreeHGlobal
.
Ecco il metodo:
public static T Deserialize<T>(byte[] messageBytes, int start, int length)
where T : struct
{
if (start + length > messageBytes.Length)
throw new ArgumentOutOfRangeException();
int typeSize = Marshal.SizeOf(typeof(T));
int bytesToCopy = Math.Min(typeSize, length);
IntPtr targetBytes = Marshal.AllocHGlobal(typeSize);
Marshal.Copy(messageBytes, start, targetBytes, bytesToCopy);
if (length < typeSize)
{
// Zero out additional bytes at the end of the struct
}
T item = (T)Marshal.PtrToStructure(targetBytes, typeof(T));
Marshal.FreeHGlobal(targetBytes);
return item;
}
Questo funziona per la maggior parte, se ho meno byte rispetto alla dimensione del struct
richiede, quindi i valori 'casuali' vengono assegnati agli ultimi campi (sto usando LayoutKind.Sequential
sul struct di destinazione). Mi piacerebbe azzerare questi campi appesi nel modo più efficiente possibile.
Per contesto, questo codice è deserializzazione messaggi multicast ad alta frequenza inviati da C ++ su Linux.
Ecco un banco di prova in mancanza:
// Give only one byte, which is too few for the struct
var s3 = MessageSerializer.Deserialize<S3>(new[] { (byte)0x21 });
Assert.AreEqual(0x21, s3.Byte);
Assert.AreEqual(0x0000, s3.Int); // hanging field should be zero, but isn't
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
private struct S3
{
public byte Byte;
public int Int;
}
Esecuzione questa prova ripetutamente provoca la seconda asserzione di riuscire con un valore diverso ogni volta.
Modifica
Alla fine, ho usato leppie di suggerimento di andare unsafe
e utilizzando stackalloc
. Questo allocato un array di byte che è stato azzerato, se necessario, e throughput migliorato tra il 50% e il 100%, a seconda della dimensione dei messaggi (messaggi più grandi scaglie maggiore beneficio).
L'ultimo metodo ha finito simile al seguente:
public static T Deserialize<T>(byte[] messageBytes, int startIndex, int length)
where T : struct
{
if (length <= 0)
throw new ArgumentOutOfRangeException("length", length, "Must be greater than zero.");
if (startIndex < 0)
throw new ArgumentOutOfRangeException("startIndex", startIndex, "Must be greater than or equal to zero.");
if (startIndex + length > messageBytes.Length)
throw new ArgumentOutOfRangeException("length", length, "startIndex + length must be <= messageBytes.Length");
int typeSize = Marshal.SizeOf(typeof(T));
unsafe
{
byte* basePtr = stackalloc byte[typeSize];
byte* b = basePtr;
int end = startIndex + Math.Min(length, typeSize);
for (int srcPos = startIndex; srcPos < end; srcPos++)
*b++ = messageBytes[srcPos];
return (T)Marshal.PtrToStructure(new IntPtr(basePtr), typeof(T));
}
}
Purtroppo questo richiede ancora una chiamata a Marshal.PtrToStructure
per convertire i byte nel tipo di destinazione.
Soluzione
Perché non solo verificare se start + length
è a typesize
?
A proposito:. Vorrei solo andare unsafe
qui e utilizzare un ciclo for per azzerare la memoria aggiuntiva
Anche questo vi darà il vantaggio di utilizzare stackalloc
che è molto più sicuro e più veloce di AllocGlobal
.
Altri suggerimenti
[DllImport("kernel32.dll")]
static extern void RtlZeroMemory(IntPtr dst, int length);
...
RtlZeroMemory(targetBytes, typeSize);
Questo funziona bene su Windows:
namespace KernelPInvoke
{
/// <summary>
/// Implements some of the C functions declared in string.h
/// </summary>
public static class MemoryWrapper
{
[DllImport("kernel32.dll", EntryPoint = "CopyMemory", SetLastError = false)]
static extern void CopyMemory(IntPtr destination, IntPtr source, uint length);
[DllImport("kernel32.dll", EntryPoint = "MoveMemory", SetLastError = false)]
static extern void MoveMemory(IntPtr destination, IntPtr source, uint length);
[DllImport("kernel32.dll", EntryPoint = "RtlFillMemory", SetLastError = false)]
static extern void FillMemory(IntPtr destination, uint length, byte fill);
}
var ptr = Marshal.AllocHGlobal(size);
try
{
MemoryWrapper.FillMemory(ptr, size, 0);
// further work...
}
finally
{
Marshal.FreeHGlobal(ptr);
}
}
Sì, come ha detto Jon Seigel, è possibile azzerare fuori usando Marshal.WriteByte
Nel seguente esempio, azzerare il buffer prima di copiare lo struct.
if (start + length > messageBytes.Length)
throw new ArgumentOutOfRangeException();
int typeSize = Marshal.SizeOf(typeof(T));
int bytesToCopy = Math.Min(typeSize, length);
IntPtr targetBytes = Marshal.AllocHGlobal(typeSize);
//zero out buffer
for(int i=0; i < typeSize; i++)
{
Marshal.WriteByte(targetBytes, i, 0);
}
Marshal.Copy(messageBytes, start, targetBytes, bytesToCopy);
Non ho mai fatto questa roba in C # prima, ma ho trovato Marshal.WriteByte (IntPtr, Int32, Byte) in MSDN. Provare che fuori.
for(int i=0; i < buffSize / 8; i += 8 )
{
Marshal.WriteInt64(buffer, i, 0x00);
}
for(int i= buffSize % 8 ; i < -1 ; i-- )
{
Marshal.WriteByte (buffer, buffSize - i, 0x00);
}
Credo che lo troverete ad essere molte volte più veloce utilizzando 64 wrights bit invece di 8 wrights bit (che è ancora necessario per gli ultimi pochi byte).
Credo che il modo migliore per azzerare un buffer è questo, se non si vuole, o non può andare dall'altra parte:
for(int i=0; i<buffSize; i++)
{
Marshal.WriteByte(buffer, i, 0x00);
}