Hi,
you must create c# struct that map your c++ struct. Add attribute
[StructLayout(La youtKind.Sequen tial)] to c# struct.
Next step is to use static methods of Marshal class to copy data from
unmanaged memory to managed memory (c# struct).
Below there is a snippet code that read from file data and copy its to a c#
struct.
Thanks to Corrado Cavalli for this snipped.
http://www.ugidotnet.org/PermaLink.a...1-ec2f2bf7d2cd
[StructLayout(La youtKind.Sequen tial)] public struct MyStruct
{
public Int32 a;
public string b;
}
public MyStruct GetStruct(strin g file)
{
byte[] indata;
Int32 size;
using (FileStream fs=new FileStream(file ,FileMode.Open) )
{
using (BinaryReader sr=new BinaryReader(fs ))
{
size=(Int32)sr. BaseStream.Leng th;
indata=new byte[size];
sr.Read(indata, 0,size);
sr.Close();
}
fs.Close();
}
IntPtr pnt=Marshal.All ocHGlobal(size) ;
GCHandle pin=GCHandle.Al loc(pnt,GCHandl eType.Pinned);
Marshal.Copy(in data,0,pnt,size );
MyStruct st2=(MyStruct) Marshal.PtrToSt ructure(pnt,typ eof(MyStruct));
pin.Free();
Marshal.FreeHGl obal(pnt);
return st2;
}
Per esportare da C# a file:
Int32 size=Marshal.Si zeOf(st);
IntPtr pnt=Marshal.All ocHGlobal(size) ;
GCHandle pin=GCHandle.Al loc(pnt);
Marshal.Structu reToPtr(st,pnt, false);
byte[] data=new byte[size];
Marshal.Copy(pn t,data,0,data.L ength);
pin.Free();
Marshal.FreeHGl obal(pnt);
using(FileStrea m fs=new FileStream(@"C: \data.bin",File Mode.Create))
{
using(BinaryWri ter sw=new BinaryWriter(fs ))
{
sw.Write(data,0 ,size);
sw.Flush();
sw.Close();
}
fs.Close();
}
"Marquee" <al*********@ho tmail.com> wrote in message
news:ce******** @odbk17.prod.go ogle.com...
Hello,
This is my first program c#, my background is c++. One thing I would
like to do is put binary data (e.g. a record from disk, or network
packet) in a struct. In C++ I would create the struct and memcpy() the
data into it thus creating a structured overlay. The struct can have
variable length e.g.
struct CRecord //Just for example
{
int m_iLength;
int m_iType;
string m_Whatever; //C++ would be like char m_Whatever[10];
byte[] m_AnyData; //Variable length field.
};
I thried this in c# with MemoryStream and BinaryFormatter , but these
methods put some .NET specific medata data into the stream. Is there a
managed way to do accomplish this?
C++ equivalent:
CRecord *NewRecord( unsigned char *pData, int cbData )
{
//Data validation here
CRecord *pRec = (CRecord*) new char( cbData );
memcpy( pRec, pData, cbData );
return( pRec);
}
Can somebody help to point out a direction/solution.
Thanx!