5

I have the following struct:

[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode)]
unsafe public struct Attributes
{

    public OrderCommand Command { get; set; }

    public int RefID { get; set; }

    public fixed char MarketSymbol[30];
}

Now, I want to write characters to the field MarketSymbol:

string symbol = "test";
Attributes.MarketSymbol = symbol.ToCharArray();

The compiler throws an error, saying its unable to convert from char[] to char*. How do I have to write this? Thanks

Juergen
  • 3,489
  • 6
  • 35
  • 59
  • 1
    Maybe it helps: http://stackoverflow.com/questions/1185269/how-to-convert-fixed-byte-char100-to-managed-char-in-c. – Samich Sep 23 '11 at 13:15

1 Answers1

3

Like this:

[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode)]
public struct Attributes
{
    public OrderCommand Command { get; set; }
    public int RefID { get; set; }
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 30)]
    public string MarketSymbol;
}

Watch out for pack = 1, it is quite unusual. And good odds for CharSet.Ansi if this interops with C code.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • This does not work out. Later I marshal this structure to a Pointer with Marshal.StructureToPtr(myAttributes, Ptr, false); All other fields are doing good, except this string. – Juergen Sep 23 '11 at 13:32
  • 2
    I have no idea what "does not work out" might mean. Marshal.StructureToPtr has no trouble with a declaration like this. Be explicit about what you see going wrong. And note my comment about CharSet. – Hans Passant Sep 23 '11 at 13:37