Struct and bytes array

Hello!
There are some problems with put struct on bytes array in CompactFramework. I try to use Marshal.PtrToStructure, but it does not work in PocketPC, because attribute FieldOffset() can't work with non intersect fields in my structure(field alignment requirements ). Please, prompt me what other way exists. Thanks!


Answer this question

Struct and bytes array

  • JR Lyon

    If I get the above posts, this means that I can't use the following code to get IDbytes, but instead have to get a byte array and extract fields using BitConverter.GetBytes or Marshal.Read* etc

    <StructLayout(LayoutKind.Explicit)> _
    Public Class KernelDeviceID ' from uniqueid.h
    <FieldOffset(0)> Public Size As Integer
    <FieldOffset(4)> Public PresetIDOffset As Integer
    <FieldOffset(8)> Public PresetIDSize As Integer
    <FieldOffset(12)> Public PlatformIDOffset As Integer
    <FieldOffset(16)> Public PlatformIDSize As Integer
    <MarshalAs(UnmanagedType.ByValArray, SizeConst:=236)> _
    <FieldOffset(20)> Public IDbytes() As Byte
    <MarshalAs(UnmanagedType.ByValArray, SizeConst:=256)> _
    <FieldOffset(0)> Public Struct() As Byte
    End Class

    Thanks for any help,

    Steve


  • pixelord

    No, P/Invoke is not affected by that because alignment rules on managed and native sides are the same. Your structure does not have alignment issues.

    Also you don't need Struct field and you probably don't need any FieldOffset() attributes at all since your offsets are matching natural element size.



  • Alex Farber

    Thanks!
    I have managed memory block (array of bytes receiced from remote device) and I want to put structs on this memory without take to pieces every struct fields.

  • JesseJ

    Please clarify what exactly you're trying to do. If you're trying to pass structure to/from native code, keep in mind it is subject to same alignment requirements on a native side. If not, why do you need structure with particular alignment



  • Pinkpanther_120

    I see... Well, I'm afraid you have to take every field to pieces. You can do something like this:

    structure foo {

    public byte Byte0; // Byte @0

    private byte i0; // 4 bytes of misaligned integer @1

    private byte i1;

    private byte i2;

    private byte i3;

    public int Int1 {

    get { return (i3 << 24) | (i2 << 16) | (i1 << 8) | i0; }

    }

    }

    Watch out for endian issues in case other device can be big endian.



  • Struct and bytes array