Question

I am currently porting some native code to C#, which consists of various structures, delegates, enumerations and external method calls.

Some of the fields within structures expect certain constants to be applied to them. It seems logical to list the constants within the structure, rather than in a separate location, as this should keep everything organized, but I am unsure what effect this would have on the structure during marshaling / interoperability with native calls.

Say for example my structure was defined as such:

[StructLayout(LayoutKind.Sequential)]
public struct NATIVE_STRUCTURE
{
     public int Value;
}

Value in this instance might require one of the following constants

VALUE1 = 0x0001;
VALUE2 = 0x0002;

So is it safe for me to write these structures like so:

[StructLayout(LayoutKind.Sequential)]
public struct NATIVE_STRUCTURE
{
     public int Value;

     public const int VALUE1 = 0x0001;
     public const int VALUE2 = 0x0002;
}

Can anyone shed some light onto how this might affect the code at runtime (if at all). Thanks.

Was it helpful?

Solution

It's better to use enums. Something like this:

[StructLayout(LayoutKind.Sequential)]
public struct NATIVE_STRUCTURE
{
    public NativeFoo FooValue;
}

public enum NativeFoo
{
   VALUE1 = 0x0001,
   VALUE2 = 0x0002,
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top