Reading Attributes?

A

Alex

I have a simple enough struct..
[StructLayout(LayoutKind.Sequential)]
public struct InstallationGeneral_Lock
{
public int Case_name;
public int Run_year;
public int Inst_name;
public int Inst_loc;
public int State;
public int Weather_filename;
public int Ground_water_temp;
[MarshalAs(UnmanagedType.LPArray, SizeConst=FEDSHelper.NUM_MONTHS)]
public int[] Wind_speed;
public int latitude;
[MarshalAs(UnmanagedType.LPArray, SizeConst=FEDSHelper.NUM_BEG_END_POINTS)]
public FEDSDate_Lock[] Heat_season;
public int Apart_min_temp;
public int Common_space_temp;
public int Elevation;
}

Note that I have used the MarshalAsAttribute for a couple of fields. This is
because I eventually will be using this to pass to come unmanaged code. That
part I have gotten a good handle on and I have some proof of concept
working. I am writing some general purpose routines to do some various
things, like initialize my struct's of which there are many. I am using
reflection to do this and it's looking very promising. The Wind_Speed field
is an array as you will see and its size is determined by a constant
FEDSHelper.NUM_MONTHS. In my routine to initialize I want to set the value
to an array of size FEDSHelper.NUM_MONTHS. But I want to figure out the size
by reading the MarshalAsAttribute.SizeConst for the field. For some reason I
cannot figure out how to do it. There is a million example for custom
attributes using GetCustomAttributes but this is an intrinsic attribute.
Here is a sample of my code..

/// <summary>
/// Inits the lock struct. Each Int32 field is set to LockState.NeverVisited
/// </summary>
/// <param name="structLock">The struct lock.</param>
private void InitLockStruct(object structLock)
{
foreach(System.Reflection.FieldInfo pi in structLock.GetType().GetFields())
{
if(pi.FieldType.IsArray == false)
{
pi.SetValue(structLock,
Convert.ToInt32(Enum.Format(typeof(LockStatus), LockStatus.NeverVisitd,
"d")));
}
}
}

This works great but how do I init my array?
 
N

Nicholas Paldino [.NET/C# MVP]

Alex,

First, are you sure you don't want to declare your Wind_speed field as
ByValArray? If you use LPArray, the field will be a pointer to the array,
and the array isn't embedded in the struct.

In order to get the attribute on the field, call the GetCustomAttributes
method on the FieldInfo instance, like so:

MarshalAsAttribute m = (MarshalAsAttribute)
pi.GetCustomAttributes(typeof(MarshalAsAttribute), true));

// Get the size const field.
int sizeConst = m.SizeConst;

Hope this helps.
 

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