• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1875
  • Last Modified:

HOW-TO Marshall structure containing wchar array and char array?


I have a structure as below:

struct FooStruct
      char fooChar[10];
      wchar fooWChar[20];

I would like to marshall it ..
I tried the following:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct fooStruct
  [MarshalAs(UnmanagedType.ByValTStr, SizeConst=10)]
  public string charArray;
  [MarshalAs(UnmanagedType.ByValArray, SizeConst=20*2)]
  public string wcharArray;

But I get - Cannot marshal field 'wcharArray' of type 'fooObj.wcharArray': Invalid managed/unmanaged type combination (String fields must be paired with LPStr, LPWStr, LPTStr, BStr or ByValTStr).

If I use as below, I get junk:
  [MarshalAs(UnmanagedType.ByValTSr, SizeConst=20*2)]
  public string wcharArray;

Please help !

Note: I need the size of the struct to be 50 ( 10 + 20*2 ), and I cannot change the unmanaged struct.

  • 2
  • 2
1 Solution
what do you mean you get junk when you use UnmanagedType.ByValTSr?

Have you tried UnmanagedType.LPWStr
libin_vAuthor Commented:
I have tried LPWStr, for which I get junk again.

By junk I mean, if assigned "hello" to wcharArray, in the unmanaged dll I get non-printable characters and they keep changing on every exectution.

Maybe try just passing the byte array and converting to a string to see if you are at least passing the data correctly.

Something like this:

public byte[] wcharArray;

libin_vAuthor Commented:
I got it from this tool - http://msdn.microsoft.com/en-us/magazine/cc164193.aspx

[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, CharSet=System.Runtime.InteropServices.CharSet.Ansi)]
public struct FooStruct {
    /// char[10]
    [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst=10)]
    public string fooChar;
    /// wchar[20]
    [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValArray, SizeConst=20, ArraySubType=System.Runtime.InteropServices.UnmanagedType.I2)]
    public char[] fooWChar;

Open in new window


Featured Post

Get free NFR key for Veeam Availability Suite 9.5

Veeam is happy to provide a free NFR license (1 year, 2 sockets) to all certified IT Pros. The license allows for the non-production use of Veeam Availability Suite v9.5 in your home lab, without any feature limitations. It works for both VMware and Hyper-V environments

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now