C#ToCharArray不适用于char *

时间:2011-09-23 13:10:10

标签: c# string pointers arrays

我有以下结构:

[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];
}

现在,我想将字符写入MarketSymbol字段:

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

编译器抛出一个错误,说它无法从char []转换为char *。 我该怎么写呢? 感谢

1 个答案:

答案 0 :(得分:3)

像这样:

[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;
}

注意pack = 1,这很不寻常。如果这与C代码互操作,CharSet.Ansi的赔率很高。