473,395 Members | 1,458 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,395 software developers and data experts.

Declare array size in Struct?

I have to parse a binary file having a number of fixed records, each
record containing datas in fixed positions. I would like to parse
this binary file into an array of structures having members that
represent those fields, so that I can access the records in a
meaningful way.
Using C, I would have defined a struct that I could cast a byte array
into, which held exactly one of these fixed records. The struct would
be defined as such:
struct rec {
char index[1] ;
char padding[50];
char name[28];
};
No big deal, (rec)char_array;.

I tried to do something similar in C#, and I am getting an error
telling me that:
"Array size cannot be specified in a variable declaration"

How might I create a data structure with fixed-size members at design
time?
Do I really have to encapsulate this into a class that contains logic
to parse the record sequentially when it's instantiated?

Thanks.
Oct 20 '08 #1
4 8074
Hi Robert,

i think, you are looking for this (PInvoke Style):

[StructLayout(LayoutKind.Sequential,CharSet=CharSet .Ansi)
public struct rec
{
[MarshalAs(UnmanagedType.LPStr,SizeConst=1)]
string index; //could also be a byte
[MarshalAs(UnmanagedType.LPStr,SizeConst=50)]
string padding;//could also be a byte
[MarshalAs(UnmanagedType.LPStr,SizeConst=28)]
string name;//could also be a byte
}

then you go like this:

rec your_rec = (rec)
Marshal.PtrToStructure(ptrPointerToYourBytesBlockO fMemory,typeof(rec));
MessageBox.Show(your_rec.name);

Regards

Kerem

--
-----------------------
Beste Grüsse / Best regards / Votre bien devoue
Kerem Gümrükcü
Latest Project: http://www.codeplex.com/restarts
Latest Open-Source Projects: http://entwicklung.junetz.de
-----------------------
"This reply is provided as is, without warranty express or implied."
"robert.waters" <ro***********@gmail.comschrieb im Newsbeitrag
news:9b**********************************@t65g2000 hsf.googlegroups.com...
>I have to parse a binary file having a number of fixed records, each
record containing datas in fixed positions. I would like to parse
this binary file into an array of structures having members that
represent those fields, so that I can access the records in a
meaningful way.
Using C, I would have defined a struct that I could cast a byte array
into, which held exactly one of these fixed records. The struct would
be defined as such:
struct rec {
char index[1] ;
char padding[50];
char name[28];
};
No big deal, (rec)char_array;.

I tried to do something similar in C#, and I am getting an error
telling me that:
"Array size cannot be specified in a variable declaration"

How might I create a data structure with fixed-size members at design
time?
Do I really have to encapsulate this into a class that contains logic
to parse the record sequentially when it's instantiated?

Thanks.
Oct 20 '08 #2
On Oct 20, 2:10*am, Kerem Gümrükcü <kareem...@hotmail.comwrote:
Hi Robert,

i think, you are looking for this (PInvoke Style):

[StructLayout(LayoutKind.Sequential,CharSet=CharSet .Ansi)
public struct rec
{
* * [MarshalAs(UnmanagedType.LPStr,SizeConst=1)]
* * string index; //could also be a byte
* * [MarshalAs(UnmanagedType.LPStr,SizeConst=50)]
* * string padding;//could also be a byte
* * [MarshalAs(UnmanagedType.LPStr,SizeConst=28)]
* * string name;//could also be a byte

}

then you go like this:

rec your_rec = (rec)
Marshal.PtrToStructure(ptrPointerToYourBytesBlockO fMemory,typeof(rec));
MessageBox.Show(your_rec.name);

Regards

Kerem
Thank you, that's exactly what I needed.
Oct 20 '08 #3
On Oct 20, 2:10*am, Kerem Gümrükcü <kareem...@hotmail.comwrote:
Hi Robert,

i think, you are looking for this (PInvoke Style):

[StructLayout(LayoutKind.Sequential,CharSet=CharSet .Ansi)
public struct rec
{
* * [MarshalAs(UnmanagedType.LPStr,SizeConst=1)]
* * string index; //could also be a byte
* * [MarshalAs(UnmanagedType.LPStr,SizeConst=50)]
* * string padding;//could also be a byte
* * [MarshalAs(UnmanagedType.LPStr,SizeConst=28)]
* * string name;//could also be a byte

}

then you go like this:

rec your_rec = (rec)
Marshal.PtrToStructure(ptrPointerToYourBytesBlockO fMemory,typeof(rec));
MessageBox.Show(your_rec.name);
I have a problem: I get an 'attempted to read protected memory"
exception.
[StructLayout(LayoutKind.Sequential,CharSet=CharSet .Ansi)]
public struct PbEntry // size=385b
{
[MarshalAs(UnmanagedType.LPStr,SizeConst=1)]
string index;
[MarshalAs(UnmanagedType.LPStr,SizeConst=5)]
string nameHeader;
[MarshalAs(UnmanagedType.LPStr,SizeConst=123)]
string contactName;
[MarshalAs(UnmanagedType.LPStr, SizeConst = 11)]
string numsHeader;
[MarshalAs(UnmanagedType.LPStr, SizeConst = 49)]
string cellNumber;
[MarshalAs(UnmanagedType.LPStr, SizeConst = 49)]
string homeNumber;
[MarshalAs(UnmanagedType.LPStr, SizeConst = 49)]
string workNumber;
[MarshalAs(UnmanagedType.LPStr, SizeConst = 49)]
string otherNumber1;
[MarshalAs(UnmanagedType.LPStr, SizeConst = 49)]
string otherNumber2;
}

...... program and FileStream ('fs') set-up .....

byte[] pbData = new byte[385];
fs.Read(pbData, 0, 385);
// pbData is now populated correctly
PbEntry pb=new PbEntry();
IntPtr ptr = Marshal.AllocHGlobal(pbData.Length);
try
{
Marshal.Copy(pbData, 0, ptr, pbData.Length);
pb = (PbEntry)Marshal.PtrToStructure(ptr,
typeof(PbEntry)); // exception happens here
Console.WriteLine(pb.ToString());
}
finally
{
Marshal.FreeHGlobal(ptr);
}

Any reason why that is protected memory?

Thanks!
Oct 20 '08 #4
On Oct 20, 7:16*pm, "robert.waters" <robert.wat...@gmail.comwrote:
On Oct 20, 2:10*am, Kerem Gümrükcü <kareem...@hotmail.comwrote:
Hi Robert,
i think, you are looking for this (PInvoke Style):
[StructLayout(LayoutKind.Sequential,CharSet=CharSet .Ansi)
public struct rec
{
* * [MarshalAs(UnmanagedType.LPStr,SizeConst=1)]
* * string index; //could also be a byte
* * [MarshalAs(UnmanagedType.LPStr,SizeConst=50)]
* * string padding;//could also be a byte
* * [MarshalAs(UnmanagedType.LPStr,SizeConst=28)]
* * string name;//could also be a byte
}
then you go like this:
rec your_rec = (rec)
Marshal.PtrToStructure(ptrPointerToYourBytesBlockO fMemory,typeof(rec));
MessageBox.Show(your_rec.name);

I have a problem: I get an 'attempted to read protected memory"
exception.
* * [StructLayout(LayoutKind.Sequential,CharSet=CharSet .Ansi)]
* * public struct PbEntry *// size=385b
* * {
* * * * [MarshalAs(UnmanagedType.LPStr,SizeConst=1)]
* * * * string index;
* * * * [MarshalAs(UnmanagedType.LPStr,SizeConst=5)]
* * * * string nameHeader;
* * * * [MarshalAs(UnmanagedType.LPStr,SizeConst=123)]
* * * * string contactName;
* * * * [MarshalAs(UnmanagedType.LPStr, SizeConst = 11)]
* * * * string numsHeader;
* * * * [MarshalAs(UnmanagedType.LPStr, SizeConst = 49)]
* * * * string cellNumber;
* * * * [MarshalAs(UnmanagedType.LPStr, SizeConst = 49)]
* * * * string homeNumber;
* * * * [MarshalAs(UnmanagedType.LPStr, SizeConst = 49)]
* * * * string workNumber;
* * * * [MarshalAs(UnmanagedType.LPStr, SizeConst = 49)]
* * * * string otherNumber1;
* * * * [MarshalAs(UnmanagedType.LPStr, SizeConst = 49)]
* * * * string otherNumber2;
* * *}

..... program and FileStream ('fs') set-up .....

* * * * * * * * byte[] pbData = new byte[385];
* * * * * * * * fs.Read(pbData, 0, 385);
* * * * * * * * // pbData is now populated correctly
* * * * * * * * PbEntry pb=new PbEntry();
* * * * * * * * IntPtr ptr = Marshal.AllocHGlobal(pbData.Length);
* * * * * * * * try
* * * * * * * * {
* * * * * * * * * * Marshal.Copy(pbData, 0, ptr, pbData.Length);
* * * * * * * * * * pb = (PbEntry)Marshal.PtrToStructure(ptr,
typeof(PbEntry)); // exception happens here
* * * * * * * * * * Console.WriteLine(pb.ToString());
* * * * * * * * }
* * * * * * * * finally
* * * * * * * * {
* * * * * * * * * * Marshal.FreeHGlobal(ptr);
* * * * * * * * }

Any reason why that is protected memory?

Thanks!
Replacing UnmanagedType.LPStr with UnmanagedType.ByValTStr for each
struct member fixed this problem.
Does anyone have any idea why?
Note: the data inside the records had many nulls (\0), which I figured
wouldn't be a problem because they typically follow strings of non-
null characters, and so would fit the model of 'null-terminated ANSI
character string'.
Thank you for any input that would help.
Oct 21 '08 #5

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

Similar topics

1
by: Sam | last post by:
Hello all I have a two dimensional array (the dimensions are not known) that needs to be passed to fortran from c++, allocate the dimensions of the array in fortran code, do some filling up of...
19
by: Geetesh | last post by:
Recently i saw a code in which there was a structer defination similar as bellow: struct foo { int dummy1; int dummy2; int last }; In application the above array is always allocated at...
22
by: Wynand Winterbach | last post by:
I think every C programmer can relate to the frustrations that malloc allocated arrays bring. In particular, I've always found the fact that the size of an array must be stored separately to be a...
10
by: Adam Warner | last post by:
Hi all, With this structure that records the length of an array of pointers as its first member: struct array { ptrdiff_t length; void *ptr; };
15
by: Geoff Cox | last post by:
Hello, Can I separately declare and initialize a string array? How and where would I do it in the code below? It was created using Visual C++ 2005 Express Beta 2 ... In C# I would have ...
8
by: redefined.horizons | last post by:
I would like to have an array declaration where the size of the array is dependent on a variable. Something like this: /* Store the desired size of the array in a variable named "array_size". */...
20
by: Cyn | last post by:
Hi, I want to create a general array structure which can hold all types. Something like this: struct ARRAY { void **array; size_t size; };
1
by: peary | last post by:
Hi, everyone, I'm writing a program to discover wireless network using Windows Native Wifi API & VB.net. I have to declare the windows API in my VB.net program. The original windows...
6
by: =?Utf-8?B?QWxleGFuZGVyZmU=?= | last post by:
Hi, I have a C# program that uses an unmanaged dll that has a function similar to the signature below : void f(out MyStruct arr, out int num); // num = actual array length returned The array...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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...
0
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,...
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...
0
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
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...

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.