C# ToCharArray does not work with char*
I have the following struct:
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode)]
unsafe public struct Attribute开发者_JS百科s
{
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
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.
精彩评论