Search code examples
c#pinvokemarshallingdllimportstructlayout

Does "DefaultCharSetAttribute" apply to "StructLayoutAttribute.CharSet" too?


C# default platform invoke uses ANSI marshalling both for method parameters and struct fields strings.

System.Runtime.InteropServices contains an attribute "DefaultCharset" to change it to Unicode.

From MSDN: "Apply the DefaultCharSetAttribute attribute at the assembly level or module level to set the CharSet value for any call to DllImportAttribute that does not include a CharSet named argument specified by the user."

My question is: does this attribute set the default for "StructLayoutAttribute.CharSet" too?

Thanks!


Solution

  • Just try it:

    using System;
    using System.Runtime.InteropServices;
    
    [module: DefaultCharSet(CharSet.Unicode)]
    
    class Program {
        static void Main(string[] args) {
            var sla = typeof(Foo).StructLayoutAttribute;
            Console.WriteLine(sla.CharSet);
            Console.ReadLine();
        }
    }
    
    struct Foo { };
    

    Output:

      Unicode
    

    So yes.