473,472 Members | 2,241 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Naughtily loading the data members of a struct - when it's boxed

I have a binary file containing fixed-length records, which I
need to read into an array of structs. I've found a relatively
nice way to do this, roughly as follows (some details omitted) :

[StructLayout(LayoutKind.Explicit,Size=8)]
struct MyStruct {
[FieldOffset(0)] int field_A ;
[FieldOffset(4)] int field_B ;
}

unsafe void LoadRecord ( int jRecord, void * pStruct, int nBytes )
{
// Reads 'nBytes' bytes of data from the specified record in the file, and
// writes them to the address passed in, ie replacing the current contents
// of the struct
}

MyStruct GetMyStruct ( int jRecord )
{
MyStruct x ;
LoadRecord(jRecord,&x,8) ;
return x ;
}

This works OK, but what I'd really like to have is a completely generic
routine
that could be passed the Type of the struct, and return a newly created
instance
of that type which has been initialised by overwriting the struct fields
with data
from the file. Something like :

object GetMyGenericStruct ( int jRecord, System.Type type )
{
object tmp = System.Activator.CreateInstance(type) ;
int nBytes = System.Runtime.InteropServices.Marshal.SizeOf(type ) ;
// Assuming that 'type' is typeof(MyStruct), we now have
// a 'boxed' instance of MyStruct. Problem is, how to determine
// the address of the beginning of the struct's data ?
fixed ( void * p = ?? )
{
LoadRecord(jRecord,p,nBytes) ;
}
return tmp ;
}

Is there a safe and portable way to find the correct address ?

If not, I'll just have to wait until Generics come along ... or hard code
a 'GetMyStruct' routine for each type.

Steve.
Nov 15 '05 #1
4 1314
This is naughty

How about putting away the unsafe code and working with the built-in
serialization framework?
--
Eric Newton
C#/ASP Application Developer
http://ensoft-software.com/
er**@cc.ensoft-software.com [remove the first "CC."]

"Steve Terepin" <st***@terepin.freeserve.co.uk> wrote in message
news:uP**************@TK2MSFTNGP11.phx.gbl...
I have a binary file containing fixed-length records, which I
need to read into an array of structs. I've found a relatively
nice way to do this, roughly as follows (some details omitted) :

[StructLayout(LayoutKind.Explicit,Size=8)]
struct MyStruct {
[FieldOffset(0)] int field_A ;
[FieldOffset(4)] int field_B ;
}

unsafe void LoadRecord ( int jRecord, void * pStruct, int nBytes )
{
// Reads 'nBytes' bytes of data from the specified record in the file, and // writes them to the address passed in, ie replacing the current contents // of the struct
}

MyStruct GetMyStruct ( int jRecord )
{
MyStruct x ;
LoadRecord(jRecord,&x,8) ;
return x ;
}

This works OK, but what I'd really like to have is a completely generic
routine
that could be passed the Type of the struct, and return a newly created
instance
of that type which has been initialised by overwriting the struct fields
with data
from the file. Something like :

object GetMyGenericStruct ( int jRecord, System.Type type )
{
object tmp = System.Activator.CreateInstance(type) ;
int nBytes = System.Runtime.InteropServices.Marshal.SizeOf(type ) ;
// Assuming that 'type' is typeof(MyStruct), we now have
// a 'boxed' instance of MyStruct. Problem is, how to determine
// the address of the beginning of the struct's data ?
fixed ( void * p = ?? )
{
LoadRecord(jRecord,p,nBytes) ;
}
return tmp ;
}

Is there a safe and portable way to find the correct address ?

If not, I'll just have to wait until Generics come along ... or hard code
a 'GetMyStruct' routine for each type.

Steve.

Nov 15 '05 #2

Conventional serialisation isn't an option unfortunately, because the
binary data files are being generated by a C program (with a long
history). I don't like this unsafe approach either ... but reading the
bytes directly over the struct's memory does seem to work nicely (of
course, one needs to get the field offsets just right, and .Net
attributes handle this quite well). The really horrible part is even
*thinking* of trying to overwrite the fields of o struct while it's
boxed - which is soooo horrible I think .Net doesn't provide a way to do
it :)
*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 15 '05 #3
Hmmm, good point... perhaps try the GCHandle and or HandleRef classes in the
System.Runtime.InteropServices

another avenue could be the IntPtr class, all of which should give you a
hard pointer location to the structure's memory location...

HTH
--
Eric Newton
C#/ASP Application Developer
http://ensoft-software.com/
er**@cc.ensoft-software.com [remove the first "CC."]

"Steve Terepin" <st***@terepin.freeserve.co.uk> wrote in message
news:uV**************@TK2MSFTNGP11.phx.gbl...

Conventional serialisation isn't an option unfortunately, because the
binary data files are being generated by a C program (with a long
history). I don't like this unsafe approach either ... but reading the
bytes directly over the struct's memory does seem to work nicely (of
course, one needs to get the field offsets just right, and .Net
attributes handle this quite well). The really horrible part is even
*thinking* of trying to overwrite the fields of o struct while it's
boxed - which is soooo horrible I think .Net doesn't provide a way to do
it :)
*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!

Nov 15 '05 #4
Would Marshal.PtrToStructure work for you?

--
William Stacey, MVP

"Steve Terepin" <st***@terepin.freeserve.co.uk> wrote in message
news:uV**************@TK2MSFTNGP11.phx.gbl...

Conventional serialisation isn't an option unfortunately, because the
binary data files are being generated by a C program (with a long
history). I don't like this unsafe approach either ... but reading the
bytes directly over the struct's memory does seem to work nicely (of
course, one needs to get the field offsets just right, and .Net
attributes handle this quite well). The really horrible part is even
*thinking* of trying to overwrite the fields of o struct while it's
boxed - which is soooo horrible I think .Net doesn't provide a way to do
it :)
*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!

Nov 15 '05 #5

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

Similar topics

5
by: Craig | last post by:
Hi everyone, As a relative new-comer to the wonderful world of .NET Framework and the C# langauge I have come across something that I would like to clarify (hopefully with the help of kind...
1
by: Tom | last post by:
Couple of questions relating to boxing. Firstly, I already know that boxing is the processing of temporarily copying a ValueType (e.g. struct, enum) to the heap so that the system can treat a...
7
by: Bill | last post by:
Hello, Here is some code: I'm thinking that when storing an object in an ArrayList or Hashtable that it clones the object. This can be shown like so: // key is a generated hashcode for this...
9
by: thomson | last post by:
Hi all, Would you please explain me where will be the heap stored if it is declared inside the Class, As class is a reference type, so it gets stored on the heap, but struct is a value...
4
by: taskswap | last post by:
I'm converting an application that relies heavily on a binary network protocol. Within this protocol are a lot of byte arrays of character data, like: public unsafe struct MsgAddEntry {...
12
by: Sadeq | last post by:
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,...
12
by: Just D | last post by:
All, It was possible before in Pascal, C++, etc. to define our custom data type or redefine the existing type, like in Turbo Pascal we could assume that shortint is int and use all references to...
37
by: JohnGoogle | last post by:
Hi, Newbie question... After a recent article in VSJ I had a go at implementing a Fraction class to aid my understanding of operator overloading. After a previous message someone suggested...
0
by: raylopez99 | last post by:
I ran afoul of this Compiler error CS1612 recently, when trying to modify a Point, which I had made have a property. It's pointless to do this (initially it will compile, but you'll run into...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
1
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...
0
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,...
1
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...
0
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...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
muto222
php
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.