我正忙于将C ++中的一段代码重写为C#
当前我被困在以下位置
pCommBuf = new BYTE[nSize+SB_OEM_HEADER_SIZE+SB_OEM_DEV_ID_SIZE+SB_OEM_CHK_SUM_SIZE];
nReceivedBytes = comm_recv( pCommBuf, nSize+SB_OEM_HEADER_SIZE+SB_OEM_DEV_ID_SIZE+SB_OEM_CHK_SUM_SIZE, gCommTimeOut );
if( nReceivedBytes != nSize+SB_OEM_HEADER_SIZE+SB_OEM_DEV_ID_SIZE+SB_OEM_CHK_SUM_SIZE )
{
if(pCommBuf)
delete pCommBuf;
return PKT_COMM_ERR;
}
memcpy(Buf, pCommBuf, SB_OEM_HEADER_SIZE+SB_OEM_DEV_ID_SIZE);
memcpy(pBuf, pCommBuf+SB_OEM_HEADER_SIZE+SB_OEM_DEV_ID_SIZE, nSize);
wReceivedChkSum = *(WORD*)(pCommBuf+nSize+SB_OEM_HEADER_SIZE+SB_OEM_DEV_ID_SIZE);
到目前为止,我的代码已经完成
//memcpy(Buf, pCommBuf, SB_OEM_HEADER_SIZE+SB_OEM_DEV_ID_SIZE);
Marshal.Copy(pCommBuf, Buf, 0, (int)(SB_OEM_HEADER_SIZE + SB_OEM_DEV_ID_SIZE)); // This works
//memcpy(pBuf, pCommBuf+SB_OEM_HEADER_SIZE+SB_OEM_DEV_ID_SIZE, nSize);
我不确定在C#中如何做pCommBuf+SB_OEM_HEADER_SIZE+SB_OEM_DEV_ID_SIZE
,pCommBuff是IntPtr
,而在C ++ Byte*
答案 0 :(得分:-1)
您只需要更改第二个副本的起始偏移量即可:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace ConsoleApplication1
{
class Program
{
const int SB_OEM_HEADER_SIZE = 10;
const int SB_OEM_DEV_ID_SIZE = 10;
const int SB_OEM_CHK_SUM_SIZE = 10;
static void Main(string[] args)
{
int nSize = 1024;
byte[] nBuf = new byte[nSize];
byte[] Buf = new byte[SB_OEM_HEADER_SIZE + SB_OEM_DEV_ID_SIZE];
IntPtr pCommBuf = Marshal.AllocHGlobal(nSize + SB_OEM_HEADER_SIZE + SB_OEM_DEV_ID_SIZE + SB_OEM_CHK_SUM_SIZE);
Marshal.Copy(nBuf, 0, pCommBuf, nSize);
Marshal.Copy(pCommBuf + nSize , Buf, 0, (int)(SB_OEM_HEADER_SIZE + SB_OEM_DEV_ID_SIZE));
}
}
}