这是来自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 :(得分:1)
我不建议使用char
来存储C#中的字节(C#中的char
实际上是两个字节,因为它是unicode)。
在.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);