2011-09-23 9 views
5

Ho il seguente struct:C# ToCharArray non funziona con char *

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

Ora, voglio scrivere i caratteri al campo MarketSymbol:

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

Il compilatore genera un errore, dicendo non è in grado di convertire da char [] a char *. Come devo scrivere questo? Grazie

+1

Forse aiuta: http://stackoverflow.com/questions/1185269/how-to-convert-fixed-byte-char100-to-managed-char-in-c. – Samich

risposta

3

Ti piace questa:

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

guardare fuori per confezione = 1, è piuttosto insolito. E buone probabilità per CharSet.Ansi se questo interviene con il codice C.

+0

Questo non funziona. Successivamente porto questa struttura a un puntatore con Marshal.StructureToPtr (myAttributes, Ptr, false); Tutti gli altri campi stanno andando bene, tranne questa stringa. – Juergen

+2

Non ho idea di cosa possa significare "non funziona". Marshal.StructureToPtr non ha problemi con una dichiarazione come questa. Sii esplicito su ciò che vedi andare storto. E nota il mio commento su CharSet. –