Click here to Skip to main content
14,926,277 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:

I created a structure like this.
public struct t
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)]
            public byte[] Lname;

            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
            public byte[] T;

            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 50)]
            public byte[] ID;

            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
            public int[] DC;

            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
            public float[]GAIN;

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

            public byte[,] status;

Now I want to pass values to these structures. And wrote c# code as follows.
array[0].name = Encoding.ASCII.GetBytes("abc");
                   array[0].T= Encoding.ASCII.GetBytes ("gh");  

Is this is a correct way or not?? if not how can I pass values to corresponding array..
E.F. Nijboer 16-Apr-15 8:06am
Try executing it and you'll know if it is correct. I guess that is the whole point of this homework assignment.
Member 10994712 16-Apr-15 23:31pm
I executed it. But I got an error that Object reference not set to an instance of an object.
E.F. Nijboer 17-Apr-15 12:08pm
What did you do to initialize array[0]? How did you declare it?
Member 10994712 17-Apr-15 23:52pm
t[] array = new t[210];
Sergey Alexandrovich Kryukov 16-Apr-15 11:11am
Why all that? Do you use this structure in P/Invoke?

1 solution

If you instantiate an array, this only clears room for the number of entries in that array. No actual items are yet created. Although structs are passed by valued (copied whole) they are not automatically created on declaration. So you need to create a new struct first.
array[0] = new t();

Good luck!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900