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]
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]
Comment