Reputation: 21
I have a struct like this:
public struct SERVER_DF_PARAMETERS
{
public bool bRunState;
public bool bWideband;
public double dFrequencyRF;
public double dFrequencyStartScan;
public double dFrequencyStopScan;
public double dBandwidthIF;
public double dBandwidthDF;
public bool bNormalModeDF;
public double dThresholdLevelDF;
public double dThresholdQualityDF;
public int iAverageTimeDF;
public bool bPreAmplifierRF;
public bool bLongAntennaRF;
public int iTunerModeRF;
public int iGainRF;
public bool bAutoGainIF;
public int iManualGainIF;
public int iAutoGainCtrlTime;
public double dMaxGainAgc;
public bool bAFC;
public bool bVoiceState; //true -> On , false -> off
public bool bSquelchState; //true -> On , false -> off
public bool bStateDenoising; //true -> On , false -> off
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)]
public String strDemodulation; //AM,FM,SSB,CW,...
public double dBandwidthVoice; //in KHz
public int iBeatFreqOffset; //in Hz (BFO)
public double dGainVoice; //int dBm
public bool bClassifier; //true -> Run , false -> Stop
public int iTimeHistoryCL; //in millisecond
};
but when the program runs the order of fields is changed to this(All booleans are in top and so on):
(I added to watch to see its value )
bAFC false bool
bAutoGainIF false bool
bClassifier false bool
bLongAntennaRF false bool
bNormalModeDF true bool
bPreAmplifierRF false bool
bRunState true bool
bSquelchState false bool
bStateDenoising false bool
bVoiceState false bool
bWideband false bool
dBandwidthDF 20.0 double
dBandwidthIF 20.0 double
dBandwidthVoice 100.0 double
dFrequencyRF 100.0 double
dFrequencyStartScan 100.0 double
dFrequencyStopScan 200.0 double
dGainVoice 1.0 double
dMaxGainAgc -30.0 double
dThresholdLevelDF -130.0 double
dThresholdQualityDF 50.0 double
iAutoGainCtrlTime 1000 int
iAverageTimeDF 1000 int
iBeatFreqOffset 0 int
iGainRF 0 int
iManualGainIF 0 int
iTimeHistoryCL 1000 int
iTunerModeRF 0 int
strDemodulation "FM" string
the problem is when I want to send this struct to the server using socket and and the server is in c++ and gives the bytes of this struct. So the order of fields should'nt change.
Upvotes: 2
Views: 2042
Reputation: 4125
put
[StructLayout(LayoutKind.Sequential, Pack=1)]
before your
public struct SERVER_DF_PARAMETERS
forces the compiler to assign the structure sequentially as listed in the definition, which is what it does by default. if you specify Pack=1 then the struct will be organised so that each field is on a byte boundary and can be read a byte at a time – i.e. no packing is necessary.
Refer to Mastering C# structs, for more explanations ^^
Upvotes: 3