Marshalling Structure to Byte

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Zoser
    New Member
    • Mar 2008
    • 1

    #1

    Marshalling Structure to Byte

    When marshalling structure from C to .NET, I get the
    following error:
    System.Argument Exception: Type could not be marshaled because the
    length of an embedded array instance does not match the declared
    length in the layout.
    //////////////
    [code=c]
    [StructLayout(La youtKind::Seque ntial, Pack=1, CharSet=CharSet ::Ansi)]
    ref struct MyStruct
    {
    [MarshalAs(Unman agedType::ByVal Array, SizeConst=1024 )]
    array<Byte>^dat a;
    };
    /////////////////////////////////
    array<Byte> ^Serialize(MySt ruct ^Struct)
    {
    int len=Marshal::Si zeOf(Struct);
    IntPtr ptr=Marshal::Al locHGlobal(len) ;
    array<Byte>^ rawdatas = gcnew array<Byte>(len );
    Marshal::Struct ureToPtr(Struct ,ptr,false);
    Marshal::Copy( ptr, rawdatas, 0, len );
    Marshal::FreeHG lobal( ptr );
    return rawdatas;
    }
    /////////////////////////////
    MyStruct ^my=gcnew MyStruct;
    my->data=Encoding: :Unicode->GetBytes("Exam ple");
    Serialize(my);[/code]
    Last edited by Frinavale; Mar 10 '08, 03:34 AM. Reason: Added Code Tags
  • Frinavale
    Recognized Expert Expert
    • Oct 2006
    • 9749

    #2
    Originally posted by Zoser
    When marshalling structure from C to .NET, I get the
    following error:
    System.Argument Exception: Type could not be marshaled because the
    length of an embedded array instance does not match the declared
    length in the layout.
    //////////////
    [code=c]
    [StructLayout(La youtKind::Seque ntial, Pack=1, CharSet=CharSet ::Ansi)]
    ref struct MyStruct
    {
    [MarshalAs(Unman agedType::ByVal Array, SizeConst=1024 )]
    array<Byte>^dat a;
    };
    /////////////////////////////////
    array<Byte> ^Serialize(MySt ruct ^Struct)
    {
    int len=Marshal::Si zeOf(Struct);
    IntPtr ptr=Marshal::Al locHGlobal(len) ;
    array<Byte>^ rawdatas = gcnew array<Byte>(len );
    Marshal::Struct ureToPtr(Struct ,ptr,false);
    Marshal::Copy( ptr, rawdatas, 0, len );
    Marshal::FreeHG lobal( ptr );
    return rawdatas;
    }
    /////////////////////////////
    MyStruct ^my=gcnew MyStruct;
    my->data=Encoding: :Unicode->GetBytes("Exam ple");
    Serialize(my);[/code]
    When passing arrays between .NET and C code, you have to make sure that the data type and the array lengths are the same.

    Comment

    Working...