473,608 Members | 1,821 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Structure as byte array

Hi

I am new to C# and am rewritting some C++ code. I want to send a byte array over a serial port. The elements of the byte array are really a structure I have populated. My question is, how do I do this in C# - that is, I want to declare a byte array, assign a structure to it, and then be able to populate the structure's fields, then use the byte array

Thank you
Joe
Nov 16 '05 #1
5 21611
Joe,

Part of this depends on what the structure is made up of. If the
structure completely contains its elements (no pointers, the arrays are
embedded within the structure), then a nice little trick you can do is to
create an array that is the size of the structure in bytes. Once you do
that, create an array of structures that contains one element. Set the
element in the array of structures to your structure, and then call the
static BlockCopy method on the Buffer class. This will copy the bytes in
the structure to the array.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Joe Thompson" <an*******@disc ussions.microso ft.com> wrote in message
news:23******** *************** ***********@mic rosoft.com...
Hi,

I am new to C# and am rewritting some C++ code. I want to send a byte array over a serial port. The elements of the byte array are really a
structure I have populated. My question is, how do I do this in C# - that
is, I want to declare a byte array, assign a structure to it, and then be
able to populate the structure's fields, then use the byte array.
Thank you,
Joe

Nov 16 '05 #2
Hi Nicholas

Thank you for the reply. My structure is self contained. I don't understand what you mean by
"call the static BlockCopy method on the Buffer class"
What is the Buffer class? I don't see a method called BlockCopy in C# anywhere..

Thank you
Joe
Nov 16 '05 #3
Joe,

The Buffer class is in the System namespace, and is in the mscorlib.dll
assembly, so it is available to you by default.

The only issue is knowing how large the structure is going to be. You
can determine this programatically by using the sizeof operator in unsafe
code. You might be tempted to use the static SizeOf method on the Marshal
class. I would recommend against that, because the size of the structure in
bytes on the unmanaged end is not always the same as the structure on the
managed end.

You can refer to the sizeof operator documentation to determine the size
of the structure:

http://msdn.microsoft.com/library/de...spec_A_5_8.asp

Your code should look like this:

// The structure we want to transform into bytes.
MyStruct pobjStruct = new MyStruct();

// Do some work to set the values. Now initialize the bytes.
// pintNumberOfByt esNeededForStru cture is the number of bytes that the
structure takes up in memory.
byte[] pbytBytes = new byte[pintNumberOfByt esNeededForStru cture];

// Create an array of the structures, make it one element long, and set to
your struct.
MyStruct[] pobjStructArray = new MyStruct[1];

// Set the value in the structure.
pobjStructAway[0] = pobjStruct;

// Copy the structure into the byte array.
Buffer.BlockCop y(pobjStructArr ay, 0, pbytBytes, 0,
pintNumberOfByt esNeededForStru cture);
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m
"Joe Thompson" <an*******@disc ussions.microso ft.com> wrote in message
news:AE******** *************** ***********@mic rosoft.com...
Hi Nicholas,

Thank you for the reply. My structure is self contained. I don't understand what you mean by: "call the static BlockCopy method on the Buffer class"
What is the Buffer class? I don't see a method called BlockCopy in C# anywhere...
Thank you,
Joe

Nov 16 '05 #4
Thanks Nicholas - that's what I was looking for..

Joe
Nov 16 '05 #5
Hi Nicholas

Maybe I replied to fast. I just ran the code and got the following runtime error on the Buffer.BlockCop y line

Object must be an array of primitive

Thank you
Joe
Nov 16 '05 #6

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

Similar topics

0
1566
by: Tien Pham via .NET 247 | last post by:
(Type your message here) -------------------------------- From: Tien Pham I am having problems with intptr. Or maybe i am not using it properly. What it is that i am having problem with is the marshaling a structure to an ptr. For instance, i have a structure declared as followed: <StructLayout(LayoutKind.Sequential, Pack:=1)> Public Structure AG_Mem_Msg Public dle As Byte Public stx As Byte
9
12680
by: Charles Law | last post by:
Suppose I have a structure Private Structure MyStruct Dim el1 As Byte Dim el2 As Int16 Dim el3 As Byte End Structure I want to convert this into a byte array where
6
2616
by: James | last post by:
I am using vb.net and need to keep in memory a large data structure, so I am looking for the best option. And after several test I am pretty confused. So I will be grateful if anyone can help me. My basic need is:
14
1780
by: Dennis | last post by:
If I have a structure like; Public Structure myStructureDef Public b() as Byte Public t as String End Structure If I pass this structure, will the values in the array b be stored on the stack or will just a pointer to the array be stored on the stack? I am trying to decide whether to use Structures or Pointers. I know that M'soft
10
4979
by: David Fort | last post by:
Hi, I'm upgrading a VB6 app to VB.net and I'm having a problem with a call to a function provided in a DLL. The function takes the address of a structure which it will fill in with values. I get an error: ---------------- An unhandled exception of type 'System.NullReferenceException' occured in
6
5890
by: Aston Martin | last post by:
Hi All, ********************** My Situation ********************** I am working on project that involves passing a structure to unmanaged code from .Net world (well using C#). Perhaps an example will prove useful. structure MyStruct { // this is a complicated struct declaration in the sense
5
3787
by: =?Utf-8?B?QXlrdXQgRXJnaW4=?= | last post by:
Hi Willy, Thank you very much for your work. C++ code doesnot make any serialization. So at runtime C# code gives an serialization error at "msg_file_s sa = (msg_file_s) bf.Deserialize(ms);" I thought that it is very hard to memory map structure array. I need both read and write memory mapped file at both side of C# and C++.
6
4866
by: carles | last post by:
Hi, Here, sample code where a byte array is used to fill a particular structure: fs = File.OpenRead(path); // FileStream BITMAPFILEHEADER bfh = new BITMAPFILEHEADER(); b = new byte;
10
6361
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 and then convert that to a byte array, pass it to the device, then get a reply and then convert that to a structure. I'm having issues with making sure what I've coded is correct. Cant figure out how to define an array in structure that is a...
0
8071
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
1
8164
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8360
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6831
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6017
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5489
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
2482
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1613
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1345
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.