如何将C#结构中的unichar数组与非托管C的DLLImport一起使用

本文关键字:DLLImport 一起 数组 结构 unichar | 更新日期: 2023-09-27 18:00:23

我正试图在C#中构建一个结构以传递给非托管C++,我想知道结构中unichar数组使用的正确变量类型是什么,以及应该将其整理为什么。

我已经为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;
}

因此,如果我在C++中有以下内容

typedef struct _foo {
    void *fileId;
    unichar fileName[15];   //  UTF-16LE
} foo;

在C#中使用的正确结构是什么?

如何将C#结构中的unichar数组与非托管C的DLLImport一起使用

将结构指定为unicode结构:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct foo
{
   public IntPtr fileId;
   [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 15)]
   public string fileName;
}

我猜struct也可以,但您需要将DllImportAttribute.CharSet属性设置为Auto,否则它将默认为AnsiUnicode也可以,但除非您使用的是Windows 98或Me(无注释),否则Auto会将字符串封送为Unicode