473,765 Members | 2,172 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Reading a struct, field by field

Is there a way to read a struct field by field?

I want to write a rather general function, like:

public string EncodeStruct (struct strct)
{
....
}

which accepts a general struct type, reads it field by field, encodes
each field depending on its type (i.e. an integer field is encoding is
different than a boolean), concatenates the results into a string and
returns it.

Jan 26 '06 #1
12 3600
Sadeq wrote:
Is there a way to read a struct field by field?

I want to write a rather general function, like:

public string EncodeStruct (struct strct)
{
...
}

which accepts a general struct type, reads it field by field, encodes
each field depending on its type (i.e. an integer field is encoding is
different than a boolean), concatenates the results into a string and
returns it.


Have a look at Type.GetFields.

Note that you can't have a method signature like the one you've got at
the moment. If you're using .NET 2.0, you can do something like:

public string EncodeStruct<T> (T value) where T : struct
{
Type type = typeof(T);
...
}

If you're using 1.1, you'll probably need to take the hit of boxing the
value and make the signature of the method just EncodeStruct(ob ject
value).

Jon

Jan 26 '06 #2
Jon Skeet [C# MVP] wrote:

<snip>
Note that you can't have a method signature like the one you've got at
the moment. If you're using .NET 2.0, you can do something like:

public string EncodeStruct<T> (T value) where T : struct
{
Type type = typeof(T);
...
}

If you're using 1.1, you'll probably need to take the hit of boxing the
value and make the signature of the method just EncodeStruct(ob ject
value).


Actually, thinking about it further, you'll have to take the hit of
boxing at least once anyway, as FieldInfo.GetVa lue takes object as a
parameter.

Jon

Jan 26 '06 #3
Thanks a lot. That was of great help.

I used .NET 2.0 syntax, and now I'm able to implement my own encoder.

But another issue arose when I wanted to encode nested structs. I tried
to use it recursively, but I the compiler cannot cast the obtained
field (which is an object, in general) to a struct.

Is there a way to overcome this issue?

Jan 26 '06 #4
Sadeq <MS******@gmail .com> wrote:
Thanks a lot. That was of great help.

I used .NET 2.0 syntax, and now I'm able to implement my own encoder.

But another issue arose when I wanted to encode nested structs. I tried
to use it recursively, but I the compiler cannot cast the obtained
field (which is an object, in general) to a struct.

Is there a way to overcome this issue?


Well, why not just use it in its boxed form? As I said elsewhere, I
don't think you'll be able to get round it being boxed at some stage
anyway - you might as well take the hit once and be done with it.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jan 26 '06 #5
So, there's no way to unbox an object (a boxed struct) back to the
struct?

And another thing: Is there a way to know if an object is in fact a
boxed struct?

Jan 26 '06 #6
Why not just use binaryserialize r? Serialize to byte[], then return base64
string of that?

--
William Stacey [MVP]

"Sadeq" <MS******@gmail .com> wrote in message
news:11******** *************@g 44g2000cwa.goog legroups.com...
| Is there a way to read a struct field by field?
|
| I want to write a rather general function, like:
|
| public string EncodeStruct (struct strct)
| {
| ...
| }
|
| which accepts a general struct type, reads it field by field, encodes
| each field depending on its type (i.e. an integer field is encoding is
| different than a boolean), concatenates the results into a string and
| returns it.
|
Jan 27 '06 #7
Sadeq <MS******@gmail .com> wrote:
So, there's no way to unbox an object (a boxed struct) back to the
struct?
Yes - just cast it.
And another thing: Is there a way to know if an object is in fact a
boxed struct?


You can call GetType(), and then use IsValueType() on the returned
Type.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jan 27 '06 #8
Hi
Sorry, I was busy with a project, so I checked the answers a bit late
;) And b4 everything, thanx 4 ur answers.

I think I should clarify my problem a bit more: I want to write a
general function, which takes a struct (any type which is of type
struct is acceptable) and encodes into a string. This encoding is a
special, so I connot use .NET Serializiation.

First of all, with Jon Skeet's help, I wrote the function as follows:

public String encodeStruct<T> (T sequence) where T:struct
{
Type type;
StringBuilder sb = new StringBuilder() ;
FieldInfo[] fields = sequence.GetTyp e().GetFields() ;
foreach (FieldInfo f in fields)
{
type = f.FieldType;
if (type == typeof(int))
sb.Append(encod eInteger((int)f .GetValue(seque nce)));
else if (type == typeof(DateTime ))
sb.Append(encod eUTCTime((DateT ime)f.GetValue( sequence)));
else if (type == typeof(Boolean) )
sb.Append(encod eBoolean((Boole an)f.GetValue(s equence)));
Jan 29 '06 #9

"Sadeq" <MS******@gmail .com> wrote in message
news:11******** **************@ g47g2000cwa.goo glegroups.com.. .
Hi
Sorry, I was busy with a project, so I checked the answers a bit late
;) And b4 everything, thanx 4 ur answers.

I think I should clarify my problem a bit more: I want to write a
general function, which takes a struct (any type which is of type
struct is acceptable) and encodes into a string. This encoding is a
special, so I connot use .NET Serializiation.

First of all, with Jon Skeet's help, I wrote the function as follows:

public String encodeStruct<T> (T sequence) where T:struct
{
Type type;
StringBuilder sb = new StringBuilder() ;
FieldInfo[] fields = sequence.GetTyp e().GetFields() ;
foreach (FieldInfo f in fields)
{
type = f.FieldType;
if (type == typeof(int))
sb.Append(encod eInteger((int)f .GetValue(seque nce)));
else if (type == typeof(DateTime ))
sb.Append(encod eUTCTime((DateT ime)f.GetValue( sequence)));
else if (type == typeof(Boolean) )
sb.Append(encod eBoolean((Boole an)f.GetValue(s equence)));
.
.
.
.
.
}
return sb.ToString();
}

You see, I implemented my own encoders for many types, like Integer,
DateTime, Boolean, etc.

Everything was good till I encountered a case in which I should encode
nested structs, i.e. there was a struct within another one. Note that
the inner struct can be general too, so I did't know in advance what
kind of struct I should cast it to. First I tried something like this
(Calling encodeStruct recursively):

if(type == typeof(struct))
sb.Append(encod eStruct((struct )f.GetValue(seq uence)));

But it doesn't work for 2 reasons:
1- typeof(struct) returns error.
2- cast to "struct" returns error.

I solved the first issue using "IsValueTyp e()" function, Thanx to Jon
Skeet.

To solve the second issue, I changed the function signature so that it
accepts an object instead of the generic T, and there was no problem.
But I was wondering if I can cast a general boxed struct [in this case,
f.GetValue(sequ ence)] to a struct so that I don't have to lose this
good feature of .NET 2.0, namely generics (You know, they apply
compile-time type checking, have better performance, etc).


There are two ways to go here:

1) Semi-generic: Use a generic wrapper to ensure that it is only called from
USER code for structs. Have this wrapper call an internal, non-generic,
object version (which is recursive).

2) The XmlSerializer approach: construct a fully typesafe generic serializer
dynamically.

option 2 doesn't really buy you anything apart from efficiency because the
serializer creation method is trying to do much the same sort of operation
as the encodeStruct method.

In short - generics and reflection can never be mixed in the way you want
because using reflection necessarily means that you haven't got the compile
time types that are needed for generics.

P.S. Just thought of optuion 3: call encodeStruct<T> dynamically. It would
work but what is the point of calling a typesafe method in a non-typesafe
way.

Jan 30 '06 #10

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

Similar topics

6
6606
by: Dietrich Epp | last post by:
Are there any good modules for reading a bitstream? Specifically, I have a string and I want to be able to get the next N bits as an integer. Right now I'm using struct.unpack and bit operations, it's a bit kludgy but it gets the right results. Thanks in advance.
3
3402
by: muser | last post by:
With the following code I'm trying to read a text file (infile) and output inaccuracies to the error file (printerfile). The text file is written and stored on disk, while the printerfile has to be created when the program executes. But the compile keeps reading that it can't find the text file. Karl you wrote the original program from which this one is but a poor copy, can you or anyone else enlighten me as to why yours worked and mine...
1
1928
by: muser | last post by:
The following program reads two lines of a file in my A drive and reads no more. Can some sarmartian tell me why that is. Please copy and paste the program into your own compiler please. program is this. #include <iostream> #include <iomanip> #include <fstream>
6
1779
by: The_Kingpin | last post by:
Hi again guys, I've decided to cut my project in section and I found it way easier like this. I'm having a little problem reading struct in a file though. I think after this I'll be able to handle it on my own. Right now the file is opened correctly and I'm able to read each line and print them in a new file. My problem is to insert each struct (which are made of 6 consecutive lines) as an item in my array.
4
3852
by: Henk | last post by:
Hi, I am new to the c-programming language and at the moment I am struggling with the following: I want to read a file using fread() and then put it in to memory. I want to use a (singel) linked list to continousely (dynamically) free up more memory when needed and put the buffers with the data of the file on a sort of stack. The problem is that i have no idea how to do this.
1
2218
by: Alex | last post by:
I have a simple enough struct.. public struct InstallationGeneral_Lock { public int Case_name; public int Run_year; public int Inst_name; public int Inst_loc; public int State; public int Weather_filename;
16
3751
by: Jm.GlezdeRueda | last post by:
Hi all, Im trying to read a 24bit bmp with fread, and i have some problems.. I want to read the whole structure in one time, but i dont know why, it only reads the first member well.. I have two questions.. 1- why if i change fread(bmp1, sizeof(bmp1), 1, fin); to fread(bmp1, sizeof(struct bmp), 1, fin); i have a Segment violation ??
21
3064
by: Stephen.Schoenberger | last post by:
Hello, My C is a bit rusty (.NET programmer normally but need to do this in C) and I need to read in a text file that is setup as a table. The general form of the file is 00000000 USNIST00Z 00000000_00 0 000 000 000 0000 000 I need to read the file line by line and eventually parse out each piece of the file and store in arrays that correspond to the specific
6
3529
by: efrenba | last post by:
Hi, I came from delphi world and now I'm doing my first steps in C++. I'm using C++builder because its ide is like delphi although I'm trying to avoid the vcl. I need to insert new features to an old program that I wrote in delphi and it's a good opportunity to start with c++.
0
9568
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...
0
9398
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10156
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10007
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9951
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
8831
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...
0
5419
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3924
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
2
3531
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.