开发者

C# ToCharArray does not work with char*

开发者 https://www.devze.com 2023-04-07 04:38 出处:网络
I have the following struct: [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode)]

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号