我有这样的结构:
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
};
但是当程序运行时,字段的顺序更改为此(所有布尔值都在顶部,依此类推):
(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
问题是当我想使用套接字将此结构发送到服务器时,服务器使用c ++并提供此结构的字节。所以字段的顺序不应该改变。
答案 0 :(得分:2)
把
[StructLayout(LayoutKind.Sequential, Pack=1)]
之前
public struct SERVER_DF_PARAMETERS
强制编译器按照定义中列出的顺序分配结构,这是它默认执行的操作。如果指定 Pack = 1 ,则结构将被组织,以便每个字段位于字节边界,并且可以一次读取一个字节 - 即不需要打包
有关更多说明,请参阅Mastering C# structs ^^
答案 1 :(得分:0)
您可以使用[StructureLayout]属性:
参考是here。