473,836 Members | 1,437 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Arrays in structures

I understand that structures are value types and arrays and classes are
reference types. But what about arrays as members of structures i.e. as in
C

struct x
{
int n;
int a[100];
}

How is such a structure (e.g. declared in C++ as a field in a class)
accessed in C#?

Peter Seaman
Nov 15 '05
33 3882
Ok, I'm getting confused, do you need to pass your structures to unmanaged
code API's?
If your answer is YES, there are no other way's I showed you to do it for
now.

If you DON'T need to pass the structure to unmanaged code, you can declare
your structures with embedded structure array's, however, there is no
reason to do this, in .NET structures are value types and you should only
use them when for data items which have "value" semantics and are "small"
(System.Decimal is a good sample).

If you still want to use structures in C# ( instead of classes) with
embedded arrays of structs, and you don't want to pass these to unmanaged
code, look at (and run) the following sample:

using System;
using System.Runtime. InteropServices ;
namespace Willys
{

[StructLayout(La youtKind.Sequen tial)]

public struct _PRIVILEGE_SET
{
public uint PrivilegeCount;
public uint Control;
[MarshalAs(Unman agedType.ByValA rray, SizeConst = 2)]
public LUID_AND_ATTRIB UTES[] Privilege_1;
}

[StructLayout(La youtKind.Sequen tial)]

public struct LUID_AND_ATTRIB UTES
{
public LUID Luid;
public uint Attributes;
}

[StructLayout(La youtKind.Sequen tial)]

public struct LUID
{
public uint LowPart;
public uint HighPart;
}

public sealed class StructInspector
{
// dump serialized object or struct
public static void DisplayStruct(_ PRIVILEGE_SET ps)
{
Console.WriteLi ne("Privileges : {0}",ps.Privile geCount);
Console.WriteLi ne("Control : {0}",ps.Control );
for(int i = 0; i < ps.PrivilegeCou nt; i++)
{
Console.WriteLi ne("----------------");
Console.WriteLi ne("LUID.Low {0:x2}
",ps.Privilege_ 1[i].Luid.LowPart);
Console.WriteLi ne("LUID.High {0:x2}
",ps.Privilege_ 1[i].Luid.HighPart) ;
Console.WriteLi ne("Attributes {0:x2} ",ps.Privilege_ 1[i].Attributes);

}
}

}
class Tester
{
static void Main()
{
_PRIVILEGE_SET ps = new _PRIVILEGE_SET( );

ps.PrivilegeCou nt = 2;
ps.Privilege_1 = new LUID_AND_ATTRIB UTES[2];
ps.Control = 2;
ps.Privilege_1[0].Luid.LowPart = 11;
ps.Privilege_1[0].Luid.HighPart = 122;
ps.Privilege_1[1].Luid.LowPart = 33;
ps.Privilege_1[1].Luid.HighPart = 444;
StructInspector .DisplayStruct( ps);
}
}
}

Willy.

"Peter Seaman" <Peter MS Seaman at StableSoftware. com> wrote in message
news:eQ******** ******@tk2msftn gp13.phx.gbl...
If you really want to use C# to pass such managed structures to
unmanaged code


But I did not say I wanted to do this! All I want is the ability to
declare and use a structure containing a directly embedded array, i.e. an
array whose data is part of the structure not outside it. There are
various
consequences, for example, copying the structure would necessarily copy
all
the array data as well. I only quoted the Win32 FIND_DATA and PRIVILEGE
SET
examples as evidence for my claim that such structures are not unsual.

I conclude that this simple and common requirement is not met in C#, and I
contend that this a defect of the language. Of course you can program
round
it in various clumsy ways, just as you can program round not using
structures at all.

Peter Seaman

Nov 15 '05 #31
Sorry, but your example does not achieve the embedded arrays desired. Run
your code with 3 statements added as shown below and note that the
assignment ps1 = ps does NOT copy the arrrays. Therefore your arrays are
OUTSIDE the structure and indirectly addressed, not INSIDE the structure and
directly addressed as I require and as would be the case in C or C++.

I want to treat a1 a2 a3 in the following structure as an array. I want the
array to be INSIDE the structure just like a1 a2 and a3 are. Then I can
treat the structure as a self-contained unit.

struct

{

int n;

int a1;

int a2;

int a3;

}

At this point I give up and am happy for you to have the last word.

Peter Seaman

----- Your code with 3 statements added -------

_PRIVILEGE_SET ps = new _PRIVILEGE_SET( );

_PRIVILEGE_SET ps1 = new _PRIVILEGE_SET( ); // New statement 1. ps1
is a separate strcuture.

ps.PrivilegeCou nt = 2;

ps.Privilege_1 = new LUID_AND_ATTRIB UTES[2];

ps.Control = 2;

ps.Privilege_1[0].Luid.LowPart = 11;

ps.Privilege_1[0].Luid.HighPart = 122;

ps.Privilege_1[1].Luid.LowPart = 33;

ps.Privilege_1[1].Luid.HighPart = 444;

ps1 = ps; // New
statement 2

ps1.Privilege_1[0].Luid.LowPart = 7; // new statement 3
StructInspector .DisplayStruct( ps); // note that
ps.Privilege_1[0].Luid.LowPart is now 7 not 11.
Nov 15 '05 #32

"Peter Seaman" <Peter MS Seaman at StableSoftware. com> wrote in message
news:ue******** ******@tk2msftn gp13.phx.gbl...
Sorry, but your example does not achieve the embedded arrays desired. Run
your code with 3 statements added as shown below and note that the
assignment ps1 = ps does NOT copy the arrrays.
*** As expected, it doesn't, it copies the variable ps1 holding a reference
(or address of) to the _PRIVILEGE_SET structure type to the variable ps , so
both ps and ps1 are now pointing to the same structure (the ps struct).
Accessing the fields using ps or ps1 will yield the same result.
But what has this to do whith embedded arrays in structs?

Therefore your arrays are OUTSIDE the structure and indirectly addressed, not INSIDE the structure
and
directly addressed as I require and as would be the case in C or C++.

*** You can't, simply because structures can be stack allocated and arrays
are allways GC heap allocated in .NET.
when declaring someStruct[] myStruct; in .NET you effectively say that
myStruct holds a reference (kind of opaque pointer type) to an array of type
someStruct allocated in the GC heap.
So the parent structure will contain a reference to a GC heap allocated
array, but you can threat the structure as a single entity and the array
access syntax used is the same as in C . The only difference is that the
array fields are on the heap, but why do you care where they are?
I want to treat a1 a2 a3 in the following structure as an array. I want
the
array to be INSIDE the structure just like a1 a2 and a3 are. Then I can
treat the structure as a self-contained unit.

struct

{

int n;

int a1;

int a2;

int a3;

}
*** Like this?

{
class Tester
{
static void Main()
{
A a = new A(3); // a is a reference to a struct of type A allocated on
the stack.
a.abc[0] = 1; // same syntax as C+C++ to access members
a.abc[1] = 2; // abc points to an array of ints on the heap, abc
is a struct field on the stack
a.abc[2] = 3;
Console.WriteLi ne("{0} {1} {2}",a.abc[0], a.abc[1], a.abc[2]);
}
}

struct A
{
internal int i;
internal int[] abc;
public A(int v) { // using a struct initializer
i = 0;
abc = new int[v]; // embedded reference abc, pointing to an array of
int's on the GC heap
}
}
}

Or ... without initializer....
static void Main()
{
A a; // struct a is allocated on the stack
a.abc = new int[3]; // abc is pointing to an array of ints on the
heap, abc is a reference fields on the stack
a.i = 123; // this value is on the stack
a.abc[0] = 1; // these values are on the heap.
a.abc[1] = 2;
a.abc[2] = 3;

}
}

struct A
{
internal int i; // struct (both fields) on the stack
internal int[] abc; // abc holds a reference to an array if int's
allocated on the heap
}
}

Here 'abc' defines an array of int's, but this could be an array of structs
as well. But again you should use classes, NEVER EVER use structs for this
UNLESS you have to interop with unmanaged code.
If you really can't live without C style structs, don't use C# or VB.NET and
stay with C/C++ or ME C++.
----------
At this point I give up and am happy for you to have the last word.
*** Thank you for the kind words.
Peter Seaman

----- Your code with 3 statements added -------

_PRIVILEGE_SET ps = new _PRIVILEGE_SET( );

_PRIVILEGE_SET ps1 = new _PRIVILEGE_SET( ); // New statement 1. ps1
is a separate strcuture.

ps.PrivilegeCou nt = 2;

ps.Privilege_1 = new LUID_AND_ATTRIB UTES[2];

ps.Control = 2;

ps.Privilege_1[0].Luid.LowPart = 11;

ps.Privilege_1[0].Luid.HighPart = 122;

ps.Privilege_1[1].Luid.LowPart = 33;

ps.Privilege_1[1].Luid.HighPart = 444;

ps1 = ps; // New
statement 2

ps1.Privilege_1[0].Luid.LowPart = 7; // new statement 3
StructInspector .DisplayStruct( ps); // note that
ps.Privilege_1[0].Luid.LowPart is now 7 not 11.


Quite normal, see above (or C# is not C/C++).
Willy.
Nov 15 '05 #33
Sorry, drop previous post, some more info and several errors corrected.

Willy.

"Willy Denoyette [MVP]" <wi************ *@pandora.be> wrote in message
news:eW******** ******@TK2MSFTN GP11.phx.gbl...

"Peter Seaman" <Peter MS Seaman at StableSoftware. com> wrote in message
news:ue******** ******@tk2msftn gp13.phx.gbl...
Sorry, but your example does not achieve the embedded arrays desired.
Run
your code with 3 statements added as shown below and note that the
assignment ps1 = ps does NOT copy the arrrays.


*** As expected, it doesn't copy the arrays, it copies all structure members
from ps to ps1, also the member "ps.Privilege_1 " holding a reference (see
below) to the LUID_AND_ATTRIB UTES structure array to the "ps1.Privilege_ 1"
structure member, so
both ps.Privilege_1 and ps1.Privilege_1 are now pointing to the same
structure array (the LUID_AND_ATTRIB UTES struct).
Accessing the fields of the array struct using ps or ps1 will yield the
same result.
If you need to copy a struct you need to implement ICloneable::Clo ne, here's
a sample...

static void Main()
{
A a;
// A a = new A(3); // a on the stack
a.abc = new int[3]; // so is abc, pointing to an array on the heap
a.i = 123; // on the stack
a.abc[0] = 11;
a.abc[1] = 2;
a.abc[2] = 3;
A b = (A)a.Clone();
b.abc[0] = 7;
Console.WriteLi ne("{0} {1} {2}",a.abc[0], a.abc[1], a.abc[2]);
Console.WriteLi ne("{0} {1} {2}",b.abc[0], b.abc[1], b.abc[2]);

}
}

struct A : ICloneable
{
internal int i;
internal int[] abc;
public object Clone()
{
A obj = (A)this.Memberw iseClone();
obj.abc = new int[abc.Length];
return obj;

}
}

But again you shouldn't use struct for this in .NET, use should use classes,
also note that copy constructors don't exist in .NET and operator= semantics
are different from C/C++.
Therefore your arrays are OUTSIDE the structure and indirectly addressed, not INSIDE the structure
and
directly addressed as I require and as would be the case in C or C++.

*** You can't, simply because structures can be stack allocated and arrays
are allways GC heap allocated in .NET.
when declaring someStruct[] myStruct; in .NET you effectively say that
myStruct holds a reference (kind of opaque pointer type) to an array of type
someStruct allocated in the GC heap.
So the parent structure will contain a reference to a GC heap allocated
array, but you can threat the structure as a single entity and the array
access syntax used is the same as in C . The only difference is that the
array fields are on the heap, but why do you care where they are?
I want to treat a1 a2 a3 in the following structure as an array. I want
the
array to be INSIDE the structure just like a1 a2 and a3 are. Then I can
treat the structure as a self-contained unit.

struct

{

int n;

int a1;

int a2;

int a3;

}
*** Like this?

{
class Tester
{
static void Main()
{
A a = new A(3); // a is a struct of type A allocated on
the stack.
a.abc[0] = 1; // same syntax as C+C++ to access members
a.abc[1] = 2; // abc points to an array of ints on the heap, abc
is a struct field on the stack
a.abc[2] = 3;
Console.WriteLi ne("{0} {1} {2}",a.abc[0], a.abc[1], a.abc[2]);
}
}

struct A
{
internal int i;
internal int[] abc;
public A(int v) { // using a struct initializer
i = 0;
abc = new int[v]; // embedded reference abc, pointing to an array of
int's on the GC heap
}
}
}
.... or sample above....

Here 'abc' defines an array of int's, but this could be an array of structs
as well. But again you should use classes, NEVER EVER use structs for this
UNLESS you have to interop with unmanaged code.
If you really can't live without C style structs, don't use C# or VB.NET and
stay with C/C++ or ME C++.

----------
At this point I give up and am happy for you to have the last word.
*** Thank you for the kind words.
Peter Seaman

----- Your code with 3 statements added -------

_PRIVILEGE_SET ps = new _PRIVILEGE_SET( );

_PRIVILEGE_SET ps1 = new _PRIVILEGE_SET( ); // New statement 1. ps1
is a separate strcuture.

ps.PrivilegeCou nt = 2;

ps.Privilege_1 = new LUID_AND_ATTRIB UTES[2];

ps.Control = 2;

ps.Privilege_1[0].Luid.LowPart = 11;

ps.Privilege_1[0].Luid.HighPart = 122;

ps.Privilege_1[1].Luid.LowPart = 33;

ps.Privilege_1[1].Luid.HighPart = 444;

ps1 = ps; // New
statement 2

ps1.Privilege_1[0].Luid.LowPart = 7; // new statement 3
StructInspector .DisplayStruct( ps); // note that
ps.Privilege_1[0].Luid.LowPart is now 7 not 11.


Quite normal, see above (or C# is not C/C++).
Willy.

Nov 15 '05 #34

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

Similar topics

3
4860
by: Java script Dude | last post by:
Some programmers prefer to stay with native level data structures such as string arrays instead of using Object based data structures such as ArrayList. From and efficiency point of view. Are string arrays the most efficient way of dealing with static tabular data such as query returns? or is it more efficient to use a Recordset type data structure using say ArrayList with a Record objects? (Pardon my JDBC ignorance)
7
2465
by: Squignibbler | last post by:
Hi all, I have a question regarding the C++ programming language regarding the nature of the relationship between pointers and arrays. If the statement MyArray is functionally identical to *(MyArray+x), what statement is functionally identical to MyArray? I ask this question because when I create a dynamic array with one
1
1461
by: ORC | last post by:
Hi, I have posted almost the same message in the compact framework group, but it seems to got lost in a deep message structure :-) so I'll try again: I'll receive a byte array from a serial port. The byte arrays are actually serialized structures with alignments of 4 (pack = 4). The structures were originally written in C++ and looks e.g. like this: struct Parameters { double CreatedDate;
2
1838
by: Andrew Burlak | last post by:
Hi, Although Unsized Arrays inside structures is a non-standard feature, I like to use it :-) It seems that Unsized Arrays are broken when /Og (Global Optimization) is enabled. The problem occurs whenever the unsized array is declared as 'const'. Here is an example:
1
2530
by: Raj | last post by:
Hi, This is regarding using Arrays of UDT's in COM. The following is a short description: - We basically need a structure, struct MAIN_STRUCT which must contain a dynamic array of another struct, struct SUB_STRUCT. We have a interface function that is callable by the client, which takes a dynamic array of MAIN_STRUCT as parameter. So the problem is wrt passing around dynamic
1
1407
by: John Dann | last post by:
Is it possible in VB.net to have arrays of structures (ie UDTs) where the structure definition includes one or more arrays? Something like: Structure MyUDT ItemOne () as byte 'for example sub new(byval dimension as integer) redim itemone(dimension) end sub End structure
10
5004
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
0
1360
by: Art Cummings | last post by:
Good morning all. I just finished an assignment using structures. In this assignment I used an array of structures. What I would have liked was to use an array of structures with a function. The problem I ran into, was when the i tried to read the data in the structure I got garbage. Normally when I use arrays they retain the information that I enter once the function completes. I'm thinking that it has something to do with using the...
127
4937
by: sanjay.vasudevan | last post by:
Why are the following declarations invalid in C? int f(); int f(); It would be great if anyone could also explain the design decision for such a language restricton. Regards, Sanjay
0
9665
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
10835
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...
1
10585
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
10249
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
9367
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
6976
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
5645
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
5818
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3108
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.