marshalling a struct containing string

前端 未结 2 437
抹茶落季
抹茶落季 2020-12-22 03:38

i basically want to take int name and string age from user in c# and send it to dll method written in c which take int and char[50] arguments in it and return string .i crea

相关标签:
2条回答
  • 2020-12-22 04:29

    Within a struct, to marshal char arrays defined as char[] you should use the UnmanagedType.ByValTStr instead.

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
    public struct Argument
    {
        public int age;
    
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 50)]
        public string name;
    }
    
    0 讨论(0)
  • 2020-12-22 04:30

    You need to change your struct definition of Argument to either

    
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
    public struct Argument
    {
        public int age;
    
        [MarshalAs(UnmanagedType.LPStr, SizeConst = 50)]
        public string name;
    }
    
    

    - or -

    
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
    unsafe public struct Argument
    {
        public int age;
        fixed char name[50];
    }
    
    

    You might also find the article Default Marshaling for Strings helpful.

    0 讨论(0)
提交回复
热议问题