Click here to Skip to main content
15,885,278 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,

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

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

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

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

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

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

            public byte[,] status;
            [FieldOffset(168)]

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

Is this is a correct way or not?? if not how can I pass values to corresponding array..
Thanks..
Posted
Comments
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?
—SA

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!
 
Share this answer
 

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