Initializing Array of Structures

H

Harry Whitehouse

I have some legacy C++ code in DLL format which has simple structures like
this:

typedef struct {
int weightoz;
int rate[6];
} MYRATES;

which are subsequentally intialized by a rather long set of numbers in a
format like this:

MYRATES MySuperRates[]=
{
{16, {385, 385, 385, 385, 385, 385}},
{32, {395, 455, 490, 505, 540, 575}},
{48, {475, 605, 685, 715, 785, 855}},
{64, {530, 705, 805, 850, 945, 1035}},
{80, {585, 800, 930, 985, 1100, 1215}},
{96, {630, 885, 989, 1005, 1130, 1230}},
{112, {680, 980, 1065, 1100, 1255, 1405}},
{128, {735, 1075, 1145, 1195, 1380, 1575}},
.....
};

Then I have a simple lookup function which enters with a weight and
parameter 0 through 5 to return a rate value.

I have a good deal of data initialized this way, and I'm torn between just
writing an interop function to my C++ DLL or converting my code to an
entirely "managed" C# solution.

My problem is that I don't see how to declare an array of structures and
then initialize them. I've defined my structure like this:

[StructLayout(LayoutKind.Sequential)]

public struct MyRates{

public int weightoz;

[MarshalAs(UnmanagedType.ByValArray, SizeConst=6)]

public int [] rate;

}

But how do I go about initializing this structure of arrays? I don't seem
to have the proper syntax.

Any thoughts?

TIA

Harry
 
M

Mattias Sjögren

Harry,

Add a constructor to the struct

public struct MyRates{
public MyRates(int weightoz, int[] rate)
{
this.weightoz = weightoz;
this.rate = rate;
}
...
}

Then declare the array like this

MyRates[] MySuperRates =
{
new MyRates( 16, new int[] {385, 385, 385, 385, 385, 385} ),
new MyRates( 32, new int[] {395, 455, 490, 505, 540, 575} ),
.....
};



Mattias
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top