2013-03-28 221 views
-2

這是代碼片段從C++轉換C++代碼到C#

struct 
    { 
     short  m_nVersion; 
     short  m_nMOT_Addr; 
     q_address m_oDistribution_Q; 
     short  m_nOffset; 
     char  m_cOperator; 
     short  m_cLength; 
     long  m_lOperand; 
     char  m_cReq_Ack; 
     char  m_cReq_SeqGap; 
     char  m_cReq_AutoDereg; 
    } oSbsReg; 

    const short nMsgSize = 20; //20 byte long structure when packed 

    char sMessageBuffer[nMsgSize]; // I created stringbuilder in c# 

    memset(&oSbsReg,0,sizeof(oSbsReg)); 
    memset(sMessageBuffer,0,sizeof(sMessageBuffer)); 

    oSbsReg.m_nVersion = 20;      //Version 
    oSbsReg.m_nMOT_Addr = (short) lMot;    //MOT in which to register with 
    oSbsReg.m_oDistribution_Q.au.queue = m_oQueue.au.queue; //Current queue number 
    oSbsReg.m_oDistribution_Q.au.group = m_oQueue.au.group; //Current group 
    //changed to 0 to resolve Oswego issue when moved to DMQ 5.0 
    oSbsReg.m_nOffset = 0;       //Start byte for telegram match 
    oSbsReg.m_cOperator = PSEL_OPER_EQ;    //Exact match 
    oSbsReg.m_cLength = 4;       //Number of bytes in match 
    oSbsReg.m_lOperand = lTelegramId;    //Telegram Id to match against 
    oSbsReg.m_cReq_Ack = 1;       //TRUE: Request an acknowledge of registration 
    oSbsReg.m_cReq_SeqGap = 1;      //TRUE: Request an acknowledge of a sequence gap 
    oSbsReg.m_cReq_AutoDereg = 1;     //TRUE: Request an auto deregistration on a connection loss 

    //default compile option is 8 byte packing, didn't want to change it 
    //manually pack bytes in structure to satisfy the SBS server's expectations 
    memcpy(sMessageBuffer, &oSbsReg, 11); 
    memcpy(sMessageBuffer+11, &(oSbsReg.m_cLength), 2); 
    memcpy(sMessageBuffer+13, &(oSbsReg.m_lOperand), 7); //twenty bytes max! 

我需要在上面的C#代碼轉換,

上面我在C#中的結構創建和過初始化,但是現在我希望把它在stringbuilder變量中,與放入char數組中的結構相同。但正如你所看到的,他們使用memset和mem cpy函數。

我如何在c#中實現同樣的功能?

我怎麼能把上面的結構在stringbuilder變量c#中,我如何從結構中提取字節,並把它放在字符串生成器變量?

+0

哪個白癡給我-2等級,我問了什麼問題? – kamal 2013-03-28 09:38:23

回答

1

我不會推薦使用char s來存儲C#中的字節(在C#中實際上是兩個字節,因爲它是unicode)(在C#中爲char)。
.NET中有這種數據的數據類型,它叫做byte,它更類似於C++的char,因爲它也包含一個字節。

如果你與你的結構類型的名稱替換T,您可以將對象轉換爲字節數組像這樣的(順便說一句,你可以做一個非常有用的通用方法出這一點):

int size = Marshal.SizeOf(typeof(T)); 
byte[] rawData = new byte[size]; 

IntPtr ptr = Marshal.AllocHGlobal(size); 
Marshal.StructureToPtr(obj, ptr, true); 
Marshal.Copy(ptr, rawData, 0, size); 
Marshal.FreeHGlobal(ptr);