解决的问题:复制数组在内存中的数据到自定义结构中。
类似功能:
在C++中
原型:extern void *memcpy(void *dest, void *src, unsigned int count);
功能:由src所指内存区域复制count个字节到dest所指内存区域。
在c#中Marshal.Copy可以实现类似功能。
需要引用的單元:using System.Runtime.InteropServices;
我定義的數據結構:
public struct RUID
{
public byte[] id;
public byte status;
public RUID(int Size)//結構的構造函數
{
id = new byte[Size];
status = 0;
}
}
應用:
public class WinLable :Label
{
protected override void WndProc(ref Message m)
{
int j;
string dl = string.Empty;
string c = string.Empty;
int v=0;
temhandle = IntPtr.Zero;
strid = string.Empty;
time = string.Empty;
switch (m.Msg)
{
case WM_MSG_UID:
if ((protext == "") &&( memo==""))
{
RUID uid = new RUID(4);
IntPtr puid = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(RUID)));
Marshal.StructureToPtr(uid, puid, false);
Marshal.Copy(m.WParam, idnew, 0, 5);//Marshal.SizeOf(uid)
if (((idnew[0] ^ idnew[1] ^ idnew[2] ^ idnew[3]) & 0xC0) == (idnew[4] & 0xC0))//判斷BCC
{
strid = string.Empty;
for (j = 0; j < 4; j++)
{
c = Convert.ToString(idnew[j], 16);
if (c.Length == 1)
c = "0" + c;
if (strid.Length == 0)
strid = c;
else
strid = strid + "-" + c;
}
strid = strid.ToUpper();
v = idnew[4] & 0x0F; //電量的統計
switch (v)
{
case 0:
dl= " Empty";
break;
case 1:
dl = " 1/8";
break;
case 2:
dl = " 2/8";
break;
case 3:
dl = " 3/8";
break;
case 4:
dl = " 4/8";
break;
case 5:
dl = " 5/8";
break;
case 6:
dl = " 6/8";
break;
case 7:
dl = " 7/8";
break;
case 8:
dl = " Full";
break;
}
idFlag = false;//為true的時候執行過程
idS = LabelList.IndexOf(this.Handle);
if (idList[idS].IndexOf(strid) > -1)
{
int timeT = Convert.ToInt32(ReadTime);
DateTime dt = DateTime.Now;
time = string.Empty;
time = string.Format("{0:yyyyMMddHHmm}", dt);
long span = Convert.ToInt64(time);
long rtime = Convert.ToInt64(timeList[idS][idList[idS].IndexOf(strid)].ToString());
if (span - rtime >= timeT)//讀取時間間隔
{
if (sumList[idS].IndexOf(strid) > -1)
{
idFlag = false;
}
else
{
idFlag = true;
}
}
}
else
{
//addFlag = true;
idList[idS].Add(strid);
for (int i = 0; i < labcum; i++)
{
if (i != idS)
{
if (idList[i].IndexOf(strid) > -1)
{
timeList[i].RemoveAt(idList[i].IndexOf(strid));
idList[i].Remove(strid);
if (sumList[i].IndexOf(strid) > -1)
sumList[i].Remove(strid);
}
}
}
DateTime dt = DateTime.Now;
time = string.Format("{0:yyyyMMddHHmm}", dt);
timeList[idS].Add(time);
memo = "idList" + idS.ToString() + " 添加新數據: " + Environment.NewLine + strid + " " + time + Environment.NewLine+"電量:"+dl;
}
if (idFlag)
{
temhandle = this.Handle;
try
{
Thread ProThread = new Thread(new ThreadStart(MainForm.DbStoredP2));
ProThread.Start();
}
catch
{
memo = strid + " 線程調用出錯";
}
sumList[idS].Add(strid);
}
}
}
else
base.WndProc(ref m);
break;
default:
base.WndProc(ref m); // DefWndProc(ref m); WndProc(ref m);
break;
}
}
}
c#中Marshal.Copy方法的使用
最新推荐文章于 2025-05-14 17:41:24 发布