Note that there are some explanatory texts on larger screens.

plurals
  1. POMarshalling IntPtrs within structs in C#
    primarykey
    data
    text
    <p>I intend to model a C# class for parsing custom protocol data I receive as a raw buffer. The buffer is already at hand as a byte array. </p> <p>This parser has to cope with varying field layouts, hence some of the protocol elements are IntPtrs.</p> <p>When I try to access a pointer within a struct after mapping the raw buffer into it, I run into an access violation.</p> <p>I made up a simple example which shows the crucial part:</p> <pre><code>namespace CS_StructMarshalling { class Packet { public PacketStruct Fields; [StructLayout(LayoutKind.Explicit)] public struct PacketStruct { [FieldOffset(0)] public UInt16 Flags; [FieldOffset(2)] public IntPtr Data; } public Packet() { Fields = new PacketStruct(); } public void DecompileBinaryBuffer(ref Byte[] byteBuffer) { int size = Marshal.SizeOf(typeof(PacketStruct)); IntPtr ptr = Marshal.AllocHGlobal(size); Marshal.Copy(byteBuffer, 0, ptr, size); this.Fields = (PacketStruct)Marshal.PtrToStructure(ptr, typeof(PacketStruct)); Marshal.FreeHGlobal(ptr); } } class Program { static void Main(string[] args) { byte[] rawBuffer = new byte[] { 1, 2, 65, 66, 67, 68, 69, 70 }; Packet testPkt = new Packet(); testPkt.DecompileBinaryBuffer(ref rawBuffer); UInt16 testFlags = testPkt.Fields.Flags; String testData = Marshal.PtrToStringAnsi(testPkt.Fields.Data, 6); } } } </code></pre> <p>I just try to wrap my head around this issue, but to no avail. To my understanding, the IntPtr must be marshalled seperately, but I don't find any hints how this could be done in a clean way.</p> <p>Any pointers welcome. Thank you for your time.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload