Marshal.StructureToPtr - C#/.NET 2.x

Узнай цену своей работы

Формулировка задачи:

Пытаюсь освоить Marshal.StructureToPtr и Marshal.PtrToStructure Массивом байт я уже могу заполнить структуру:
private static structure FillStructure<structure>(byte[] Buffer)
        {
            structure Ret;
            GCHandle handle = GCHandle.Alloc(Buffer, GCHandleType.Pinned);
            Ret = (structure)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(structure));
            handle.Free();
            return Ret;
        }
а вот наоборот не получается, вылетает без ошибок.
private static byte[] FillBytes<structure>(structure Buffer)
        {
            byte[] Ret = new byte[Marshal.SizeOf(typeof(structure))];
            var ptr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(structure)));
            Marshal.StructureToPtr(Ret, ptr, true);
            return Ret;
        }

Решение задачи: «Marshal.StructureToPtr»

textual
Листинг программы
[StructLayout(LayoutKind.Sequential, Pack = 1)]
private struct _Request
{
   public UInt16 A01_Function;
   public UInt32 A02_Direction;
   public byte A03_Request;
   public UInt16 A04_Value;
   public UInt16 A05_Index;
   public UInt32 A06_Length;
}

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

6   голосов , оценка 3.833 из 5
Похожие ответы