Search code examples
pinvoke

How to set c# struct attribute (StructLayoutAttribute) globally?


I'm working on a c# p/invoke project and defining a lot of structures. For each structure, I'm using:

    [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, Pack = 1)]

But Now I'd like to set the attribute(Pack = 1) only once so that all my structures share the same setting, How can I do that?

Thanks, Fei


Solution

  • You cannot do that. There is no global switch. You have to set Pack explicitly on every struct.

    You can at least make you code more concise by adding a using statement, and by writing StructLayout rather than StructLayoutAttribute:

    using System.Runtime.InteropServices;
    
    ....
    [StructLayout(LayoutKind.Sequential, Pack = 1)]