简体   繁体   English

如何在非托管C的DLLImport的C#结构中使用unichar数组

[英]How to use unichar array in C# struct with DLLImport of unmanaged C

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. 我试图在C#中构建一个结构以传递给非托管C ++,我想知道在我的结构中用于unichar数组的变量的正确类型是什么,应该将其编组为什么。

I have already figured this out for an unsigned char array 我已经想通了unsigned char array

C/C++ C / C ++

typedef struct _foo {
    void *fileId;
    unsigned char   fileName[15];
} foo;

C# 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++ 所以如果我在C ++中有以下内容

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

What would be the correct struct to use in C#? 在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 . 我猜想相同的struct也可以,但是您需要将DllImportAttribute.CharSet属性设置为Auto ,否则将默认设置为Ansi Unicode would do too, but unless you are using Windows 98 or Me (no comments) Auto will marshal strings as Unicode . Unicode也可以,但是除非您使用Windows 98或Me(无注释),否则Auto会将字符串封送为Unicode

Specify the structure as a unicode structure: 将结构指定为unicode结构:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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