Search code examples
c#structdllimportunichar

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.

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#?


Solution

  • 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;
    }