Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# ToCharArray does not work with char*

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

like image 866
Juergen Avatar asked Oct 23 '22 23:10

Juergen


1 Answers

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.

like image 172
Hans Passant Avatar answered Nov 12 '22 21:11

Hans Passant