BOOL SetByteArrayToVariant(VARIANT* v, BYTE* lpByteArray, int nLength)
{
try
{
SAFEARRAY* psa = NULL;
SAFEARRAYBOUND rgsabound[1];
rgsabound[0].lLbound = 0;
rgsabound[0].cElements = nLength;
psa = SafeArrayCreate(VT_UI1, 1, rgsabound);
for(long i=0; i<nLength; i++)
SafeArrayPutElement(psa, &i, &lpByteArray[i]);
v->vt = VT_ARRAY | VT_UI1;
v->parray = psa;
}
catch(...)
{
return FALSE;
}
return TRUE;
}
//发送
void Send(String strSend)
{
String s = strSend;
strSend ="";
s =s.Trim();
s = StringReplace(s," ","",TReplaceFlags()<<rfReplaceAll<<rfIgnoreCase);
int len = s.Length();
Byte Data[255];
int size=0;
for(int i=1;i<=len;i++)
{
if(i%2==0)
{
String bb;
bb="0x";
bb+=s[i-1];
bb+=s[i];
Data[size]=StrToInt(bb);
strSend+=IntToHex(Data[size],2)+" ";
size++;
}
}
VARIANT v;
VariantInit(&v);
SetByteArrayToVariant(&v, Data, size);
Form1->MSComm1->Output =(OleVariant) v;
}
//接收
void __fastcall TForm1::MSComm1Comm(TObject *Sender)
{
AnsiString str;
OleVariant s;
switch(MSComm1->CommEvent)
{
case comEvSend:
break;
case comEvReceive:
{
int count=MSComm1->InBufferCount; //字节数
DebugMsg("接收字节数:"+IntToStr(count));
if(MSComm1->InBufferCount>0)// 是否有字符驻留在接收缓冲区等待被取出
{
s=MSComm1->Input;//接收数据
if(MSComm1->InputMode==comInputModeBinary) // 1
{
AnsiString st1="";
Byte buf[128];
for(int j=0;j<count; j++)
{
buf[j]=s.GetElement(j); //转换成字节类型
st1+=IntToHex(buf[j],2)+" ";
}
DebugMsg("接收数据:"+st1);
}
}
}
break;
default:
break;
}
}