I am trying to build a struct in C# to pass to unmanaged C++, I was wondering what is the correct type of variable to use for a unichar
array in my struct and what it should be marshalled as.
I have already figured this out for an unsigned char array
C/C++
typedef struct _foo {
void *fileId;
unsigned char fileName[15];
} foo;
C#
[StructLayout(LayoutKind.Sequential)]
public struct foo
{
public IntPtr fileId;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 15)]
public string fileName;
}
So if I have the following in C++
typedef struct _foo {
void *fileId;
unichar fileName[15]; // UTF-16LE
} foo;
What would be the correct struct to use in C#?
I'm guessing the same struct
would do, but you need to set the DllImportAttribute.CharSet
property to Auto
or it will default to Ansi
. Unicode
would do too, but unless you are using Windows 98 or Me (no comments) Auto
will marshal strings as Unicode .
Specify the structure as a unicode structure:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct foo
{
public IntPtr fileId;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 15)]
public string fileName;
}
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.