简体   繁体   中英

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?

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)]
class A {
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 24)]
    public string Name;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM