最近做了一个网络编程的DLL给C#调用,DLL中封装了一个TCP Client的函数接口,如下所示
//C++ TCP报文发送接口
int TcpClient_send(unsigned char* buffSend, unsigned int nLen)
{
unsigned char buff[1024];
int len = StringToHex(buffSend, buff);
int nRet = 0;
if (Connect())
{
int sendRes = send(m_hTcpClientSocket, (char*)buff, nLen, 0);
if (sendRes == SOCKET_ERROR)
{
nRet = -2;
closesocket(m_hTcpClientSocket);
m_hTcpClientSocket = NULL;
}
else
{
nRet = sendRes;
}
}
else
{
nRet = -1;
}
return nRet;
}
char ConvertHexChar(char ch)
{
if ((ch >= '0') && (ch <= '9'))
return ch - 0x30;
else if ((ch >= 'A') && (ch <= 'F'))
return ch - 'A' + 10;
else if ((ch >= 'a') && (ch <= 'f'))
return ch - 'a' + 10;
else return (-1);
}
int StringToHex(CString str, unsigned char* senddata)
{
int hexdata, lowhexdata;
int hexdatalen = 0;
int len = str.GetLength();
for (int i = 0; i < len;)
{
char lstr, hstr = str[i];
if (hstr == ' ')
{
i++;
continue;
}
i++;
if (i >= len)
break;
lstr = str[i];
hexdata = ConvertHexChar(hstr);
lowhexdata = ConvertHexChar(lstr);
if ((hexdata == 16) || (lowhexdata == 16))
break;
else
hexdata = hexdata * 16 + lowhexdata;
i++;
senddata[hexdatalen] = (char)hexdata;
hexdatalen++;
}
return hexdatalen;
}
在C#中调用该接口的时候,刚开始我是通过string down = System.Text.Encoding.Default.GetString()或者System.Text.Encoding.UTF8.GetString()的方式将字节数组转换成string然后传递给TcpClientSyn_send函数,但是这两种方法传递的字节数组到达DLL中时大于127的字节都会变为0x3f也就是63。后来果断抛弃该种方法,转而通过自定义函数BytesToHexString()将字节数组变为类似于"AA AA A0 01"这样的字符串,然后再DLL中通过另一个自定义函数StringToHex()来再次转换成字节数组。
//C#调用DLL中的TcpClient_send函数
private static void SendThread(object n)
{
//发送
byte[] buffSend = { 0xAA, 0xAA, 0x70, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x80, 0x17, 0xC5, 0x51, 0xE2, 0xEE, 0xEE };
//string down = System.Text.Encoding.Default.GetString(buffSend);
//string down = System.Text.Encoding.UTF8.GetString(buffSend);
string HexString_down = BytesToHexString(buffSend);
int sendLen=TcpClient_send(HexString_down, 16);
if (sendLen> 0)
{
}
//接收
uint nRecvLen;
nRecvLen = 0;
StringBuilder buffRecv = new StringBuilder(1024);
buffRecv.Clear();
int recvLen=TcpClientSyn_recv(buffRecv,ref nRecvLen);
if (recvLen> 0)
{
}
}
private static string BytesToHexString(byte[] byteDatas)
{
StringBuilder builder = new StringBuilder();
for (int i = 0; i < byteDatas.Length; i++)
{
builder.Append(string.Format("{0:X2} ", byteDatas[i]));
}
return builder.ToString().Trim();
}