Tài Đinh
Tài Đinh

Reputation: 11

Convert array wchar_t in c++ to array string in C#

I have two structs one in C++ and another in C#, defined as below:

In C:

struct A {
  wchar_t Name[24];
} 

In C#:

[StructLayout(LayoutKind.Sequential)]
class A {
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 24*2)]
    public char[] Name;
}

When I use Marshal.PtrToStructure to convert the struct from C++ to C#, I get garbage characters in the string. What is causing this problem?

Upvotes: 1

Views: 373

Answers (1)

jwezorek
jwezorek

Reputation: 9535

Here is microsoft's documentation on marshalling strings of different types. The case you are looking for, fixed size unicode, would be like

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
class A {
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 24)]
    public string Name;
}

Upvotes: 1

Related Questions