473,325 Members | 2,442 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,325 software developers and data experts.

How can I map byte[] data to struct data (preferably using managed code)

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!

Nov 16 '05 #1
1 3625
Hi,
you must create c# struct that map your c++ struct. Add attribute
[StructLayout(LayoutKind.Sequential)] 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(LayoutKind.Sequential)] public struct MyStruct
{
public Int32 a;
public string b;
}
public MyStruct GetStruct(string file)
{
byte[] indata;
Int32 size;
using (FileStream fs=new FileStream(file,FileMode.Open))
{
using (BinaryReader sr=new BinaryReader(fs))
{
size=(Int32)sr.BaseStream.Length;
indata=new byte[size];
sr.Read(indata,0,size);
sr.Close();
}
fs.Close();
}
IntPtr pnt=Marshal.AllocHGlobal(size);
GCHandle pin=GCHandle.Alloc(pnt,GCHandleType.Pinned);
Marshal.Copy(indata,0,pnt,size);
MyStruct st2=(MyStruct) Marshal.PtrToStructure(pnt,typeof(MyStruct));
pin.Free();
Marshal.FreeHGlobal(pnt);
return st2;
}

Per esportare da C# a file:

Int32 size=Marshal.SizeOf(st);
IntPtr pnt=Marshal.AllocHGlobal(size);
GCHandle pin=GCHandle.Alloc(pnt);
Marshal.StructureToPtr(st,pnt,false);
byte[] data=new byte[size];
Marshal.Copy(pnt,data,0,data.Length);
pin.Free();
Marshal.FreeHGlobal(pnt);
using(FileStream fs=new FileStream(@"C:\data.bin",FileMode.Create))
{
using(BinaryWriter sw=new BinaryWriter(fs))
{
sw.Write(data,0,size);
sw.Flush();
sw.Close();
}
fs.Close();
}


"Marquee" <al*********@hotmail.com> wrote in message
news:ce********@odbk17.prod.google.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!

Nov 16 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

13
by: Ray Z | last post by:
So far, I get the idea that if I want to use both the unmanaged and managed memory, I can not avoid memory copy. But I DO need to avoid it. I get a idea that maybe I could use "union" to convert...
3
by: Pablo Gutierrez | last post by:
I have a C# method that reads Binary data (BLOB type) from a database and returns the data an array of bytes (i.e byte outbyte = new byte;). The BLOB column is saved into the database by a C...
8
by: Ben Terry | last post by:
What's the most efficient way to transfer data from a byte to a struct? The struct is rather complex--contains other structs as well as byte members. I've tried to use Marshal.Copy and an IntPtr...
5
by: Amil Hanish | last post by:
I have a huge byte array from another API that contains structs of differing sizes. I'd like to create n structs based on data in the byte array. But how? For example, if I want to take bytes...
1
by: Maury Markowitz | last post by:
Thanks to a tremendous amount of patient help from Rob over in the interop group I have managed to successfully wrap a vendor-provided DLL and call it successfully from managed C# code. Now I'd...
5
by: Maury Markowitz | last post by:
I have a byte returned from a DLL that contains n c-style strings inside it. Any suggestions on how to easily pull them out into a string? Encoding helps with a single byte array (although easily...
17
by: =?Utf-8?B?U2hhcm9u?= | last post by:
Hi Gurus, I need to transfer a jagged array of byte by reference to unmanaged function, The unmanaged code should changed the values of the array, and when the unmanaged function returns I need...
24
by: ThunderMusic | last post by:
Hi, The subject says it all... I want to use a byte and use it as byte* so I can increment the pointer to iterate through it. What is the fastest way of doing so in C#? Thanks ThunderMusic
10
by: Scott Townsend | last post by:
So I need to talk to a devices that expects all of the bits and bytes I sent it to be in specific places (not yet 100% defined). I wanted to create a structure/class with all of the data in it...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.