473,769 Members | 1,674 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 8104
Hi Robert,

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

[StructLayout(La youtKind.Sequen tial,CharSet=Ch arSet.Ansi)
public struct rec
{
[MarshalAs(Unman agedType.LPStr, SizeConst=1)]
string index; //could also be a byte
[MarshalAs(Unman agedType.LPStr, SizeConst=50)]
string padding;//could also be a byte
[MarshalAs(Unman agedType.LPStr, SizeConst=28)]
string name;//could also be a byte
}

then you go like this:

rec your_rec = (rec)
Marshal.PtrToSt ructure(ptrPoin terToYourBytesB lockOfMemory,ty peof(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.wat ers" <ro***********@ gmail.comschrie b im Newsbeitrag
news:9b******** *************** ***********@t65 g2000hsf.google groups.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...@hotm ail.comwrote:
Hi Robert,

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

[StructLayout(La youtKind.Sequen tial,CharSet=Ch arSet.Ansi)
public struct rec
{
* * [MarshalAs(Unman agedType.LPStr, SizeConst=1)]
* * string index; //could also be a byte
* * [MarshalAs(Unman agedType.LPStr, SizeConst=50)]
* * string padding;//could also be a byte
* * [MarshalAs(Unman agedType.LPStr, SizeConst=28)]
* * string name;//could also be a byte

}

then you go like this:

rec your_rec = (rec)
Marshal.PtrToSt ructure(ptrPoin terToYourBytesB lockOfMemory,ty peof(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...@hotm ail.comwrote:
Hi Robert,

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

[StructLayout(La youtKind.Sequen tial,CharSet=Ch arSet.Ansi)
public struct rec
{
* * [MarshalAs(Unman agedType.LPStr, SizeConst=1)]
* * string index; //could also be a byte
* * [MarshalAs(Unman agedType.LPStr, SizeConst=50)]
* * string padding;//could also be a byte
* * [MarshalAs(Unman agedType.LPStr, SizeConst=28)]
* * string name;//could also be a byte

}

then you go like this:

rec your_rec = (rec)
Marshal.PtrToSt ructure(ptrPoin terToYourBytesB lockOfMemory,ty peof(rec));
MessageBox.Show (your_rec.name) ;
I have a problem: I get an 'attempted to read protected memory"
exception.
[StructLayout(La youtKind.Sequen tial,CharSet=Ch arSet.Ansi)]
public struct PbEntry // size=385b
{
[MarshalAs(Unman agedType.LPStr, SizeConst=1)]
string index;
[MarshalAs(Unman agedType.LPStr, SizeConst=5)]
string nameHeader;
[MarshalAs(Unman agedType.LPStr, SizeConst=123)]
string contactName;
[MarshalAs(Unman agedType.LPStr, SizeConst = 11)]
string numsHeader;
[MarshalAs(Unman agedType.LPStr, SizeConst = 49)]
string cellNumber;
[MarshalAs(Unman agedType.LPStr, SizeConst = 49)]
string homeNumber;
[MarshalAs(Unman agedType.LPStr, SizeConst = 49)]
string workNumber;
[MarshalAs(Unman agedType.LPStr, SizeConst = 49)]
string otherNumber1;
[MarshalAs(Unman agedType.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.AllocHG lobal(pbData.Le ngth);
try
{
Marshal.Copy(pb Data, 0, ptr, pbData.Length);
pb = (PbEntry)Marsha l.PtrToStructur e(ptr,
typeof(PbEntry) ); // exception happens here
Console.WriteLi ne(pb.ToString( ));
}
finally
{
Marshal.FreeHGl obal(ptr);
}

Any reason why that is protected memory?

Thanks!
Oct 20 '08 #4
On Oct 20, 7:16*pm, "robert.wat ers" <robert.wat...@ gmail.comwrote:
On Oct 20, 2:10*am, Kerem Gümrükcü <kareem...@hotm ail.comwrote:
Hi Robert,
i think, you are looking for this (PInvoke Style):
[StructLayout(La youtKind.Sequen tial,CharSet=Ch arSet.Ansi)
public struct rec
{
* * [MarshalAs(Unman agedType.LPStr, SizeConst=1)]
* * string index; //could also be a byte
* * [MarshalAs(Unman agedType.LPStr, SizeConst=50)]
* * string padding;//could also be a byte
* * [MarshalAs(Unman agedType.LPStr, SizeConst=28)]
* * string name;//could also be a byte
}
then you go like this:
rec your_rec = (rec)
Marshal.PtrToSt ructure(ptrPoin terToYourBytesB lockOfMemory,ty peof(rec));
MessageBox.Show (your_rec.name) ;

I have a problem: I get an 'attempted to read protected memory"
exception.
* * [StructLayout(La youtKind.Sequen tial,CharSet=Ch arSet.Ansi)]
* * public struct PbEntry *// size=385b
* * {
* * * * [MarshalAs(Unman agedType.LPStr, SizeConst=1)]
* * * * string index;
* * * * [MarshalAs(Unman agedType.LPStr, SizeConst=5)]
* * * * string nameHeader;
* * * * [MarshalAs(Unman agedType.LPStr, SizeConst=123)]
* * * * string contactName;
* * * * [MarshalAs(Unman agedType.LPStr, SizeConst = 11)]
* * * * string numsHeader;
* * * * [MarshalAs(Unman agedType.LPStr, SizeConst = 49)]
* * * * string cellNumber;
* * * * [MarshalAs(Unman agedType.LPStr, SizeConst = 49)]
* * * * string homeNumber;
* * * * [MarshalAs(Unman agedType.LPStr, SizeConst = 49)]
* * * * string workNumber;
* * * * [MarshalAs(Unman agedType.LPStr, SizeConst = 49)]
* * * * string otherNumber1;
* * * * [MarshalAs(Unman agedType.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.AllocHG lobal(pbData.Le ngth);
* * * * * * * * try
* * * * * * * * {
* * * * * * * * * * Marshal.Copy(pb Data, 0, ptr, pbData.Length);
* * * * * * * * * * pb = (PbEntry)Marsha l.PtrToStructur e(ptr,
typeof(PbEntry) ); // exception happens here
* * * * * * * * * * Console.WriteLi ne(pb.ToString( ));
* * * * * * * * }
* * * * * * * * finally
* * * * * * * * {
* * * * * * * * * * Marshal.FreeHGl obal(ptr);
* * * * * * * * }

Any reason why that is protected memory?

Thanks!
Replacing UnmanagedType.L PStr with UnmanagedType.B yValTStr 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
6433
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 the array in fortran and then accessing it in my c++ code. Say in my c++ code I have; extern "C" { void foo_(float **, int &, int &); }
19
3082
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 runtime using malloc.In this last member of the structer "int last" is not
22
2465
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 nightmare. There are of course many solutions, but they all end up forcing you to abandon the array syntax in favour of macros or functions. Now I have two questions - one is historical, and the other practical. 1.) Surely malloc (and...
10
6693
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
5323
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 private string myArray;
8
10167
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". */ unsigned short int array_size = 25; /*Declare an array named "numbers" using the variable initialized above. */ unsigned short int numbers;
20
2326
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
2133
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 declaration is as below. The problem is in "struct _WLAN_AVAILABLE_NETWORK_LIST", it declared "WLAN_AVAILABLE_NETWORK Network;". I think which means a Network array of struct WLAN_AVAILABLE_NETWORK.
6
8967
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 must be allocated (with known max length = 10) before the call to the dll function (the dll just fills it ,with no allocations). The definitions of Mystruct and :
0
9589
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
9423
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,...
1
9994
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
9863
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
6673
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();...
0
5298
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5447
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3958
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
3561
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.