首页 ┆ 网站地图 ┆ 在线留言 ┆ 游戏资讯 ┆ 资源下载 ┆ 端午节祝福 ┆ 迅雷在线影视 ┆淘宝手机在线充值 ┆淘宝游戏点卡充值 
设为首页
加入收藏
联系我们
高级搜索
您当前的位置: 主页>NET专区>C#语言>C#调用C++的函数实现串口通信读写操作
C#调用C++的函数实现串口通信读写操作
来源: 发布时间:2008-11-14 发布人: 浏览: 人次   字体: [ ]  

今天在xiangding博客上看到一篇用关在C#语言中调用C++的函数来与串口通信的文章,不错,就转载过来了,具体内容是:用C#来实现主程序,主要的功能是与一些通信设备打交道,当然就是通过串口了,以十进制发送和读取串口的数据,考虑到C#调用API并没有C++来得方便,因此,我用C++封装了一个读写串口的DLL,只提供一个函数供外部调用,这样的好处在于,C#只要调用这个函数发送完数据后,函数立即就能获得串口返回的数据。另一个好处在于,一些不熟悉C++的朋友,也能够直接通过这个DLL来对串口做一些操作。

   杂话就不多讲了,直接贴这个读写串口的dll代码:

 一. C++部分:
  1)头文件:
   // SerialPortSync.h: interface for the CSerialPortSync class.
//
//////////////////////////////////////////////////////////////////////

#if !defined(AFX_SERIALPORTSYNC_H__7FC698BB_BF4D_449E_8DE9_62B8876187CF__INCLUDED_)
#define AFX_SERIALPORTSYNC_H__7FC698BB_BF4D_449E_8DE9_62B8876187CF__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

class CSerialPortSync 
{
public:
 CSerialPortSync();
public:
 bool Open(int nPort, int nBaud,int nDatabit, int nStopbit, int nParity, int nTimeOut = 500);
 DWORD SendData(const char *buffer, const unsigned int writebytes, char *RecBuffer, int nSendType = 1);
 void Close();
private:
 HANDLE m_hCom; //串口句柄
 bool m_bOpened;

 char ConvertHexChar(char ch);
 int String2Hex(const char *str, const unsigned int nLen, byte *senddata);
};

#endif // !defined(AFX_SERIALPORTSYNC_H__7FC698BB_BF4D_449E_8DE9_62B8876187CF__INCLUDED_)

 

 2). CPP文件:

// SerialPortSync.cpp: implementation of the CSerialPortSync class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
//#include "SerialPortDemo.h"
#include "SerialPortSync.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
#define MAXSENDLENGTH 20
#define MAXRECEIVELENGTH 20

CSerialPortSync::CSerialPortSync()
{
 m_bOpened = false;
}

/******************************************************************************
*函数功能:打开串口,设置串口参数
*参数说明:
    nCom:操作的串口值,如COM1:,COM2:等等
    lnBaudrate: 波特率
    nStopbits: 停止位
    nDatabits: 数据位
    nParity:奇偶校验
*返回值: 返回串口的句柄
*时间:2008/10/22
*作者:XiangDing
*****************************************************************************/
bool CSerialPortSync::Open(int nPort, int nBaud,int nDatabit,int nStopbit,int nParity, int nTimeOut)
{
 if( m_bOpened ) return( true );

 char strPort[10]={0};
 sprintf(strPort,"COM%d",nPort);

 m_hCom=CreateFile(strPort, GENERIC_READ|GENERIC_WRITE, 0, NULL ,OPEN_EXISTING, 0,NULL);
 if ((m_hCom==INVALID_HANDLE_VALUE) || (m_hCom==NULL ))
 {
  m_bOpened = false;
  return false;
 }

    COMMTIMEOUTS ct;
    ct.ReadIntervalTimeout         = MAXDWORD;                                  //设置超时设置
    ct.ReadTotalTimeoutMultiplier  = 0;
    ct.ReadTotalTimeoutConstant    = nTimeOut;
    ct.WriteTotalTimeoutMultiplier = 0;
    ct.WriteTotalTimeoutConstant   = nTimeOut;
 SetCommTimeouts( m_hCom, &ct );

 DCB dcb;
 GetCommState( m_hCom, &dcb );
    dcb.BaudRate           = nBaud;
    dcb.StopBits           = nStopbit;
    dcb.Parity             = nParity;
    dcb.ByteSize           = (BYTE)nDatabit;       // number of bits/byte, 4-8

 BOOL bl = SetCommState( m_hCom, &dcb );

 m_bOpened = TRUE;
 
 return true;
}

// nSendType 1: 以十六进制发送.  0: 直接发送字符串
//返回值是已接收的个数
//返回 -1: 写串口失败. -2:清除串口错误;  -3: 串口返回数据为0;
DWORD CSerialPortSync::SendData(const char *sendBuffer, const unsigned int writebytes, char *RecBuffer, int nSendType)
{

 if( !m_bOpened ) return 0;
 
    DWORD dwWritten = 0;
    DWORD dwError;
 DWORD dwBytesRead = 0;


 if (nSendType == 1)
 {
  byte bHexData[MAXSENDLENGTH] = {0};
  memset(bHexData, 0, MAXSENDLENGTH);

  int len = String2Hex(sendBuffer, writebytes, bHexData);
  BOOL bWriteRet = FALSE;
        bWriteRet = WriteFile(m_hCom, bHexData, len, &dwWritten, NULL);
 
  BOOL bReadStatus;
  BYTE bReadBuf[MAXRECEIVELENGTH] = {0};

  bReadStatus = ReadFile( m_hCom, bReadBuf, MAXRECEIVELENGTH, &dwBytesRead, NULL);
 
  if (dwBytesRead <1 ) return dwBytesRead;

  CString strBuf;
  CString strTemp;
  for(int i=0; i<dwBytesRead; i++ )
  {
   strTemp.Format("%02X", bReadBuf[i]);
   strBuf += strTemp;
  }
  strBuf.TrimRight();
  strncpy(RecBuffer, (LPCTSTR)strBuf, dwBytesRead * 2 + 1);

  return dwBytesRead;
 }
 return dwBytesRead;
}

void CSerialPortSync::Close()
{                                                                              
    if(m_hCom != INVALID_HANDLE_VALUE)
    {
        CloseHandle(m_hCom);
  m_hCom = INVALID_HANDLE_VALUE;
    }

 if( m_bOpened ) m_bOpened = false;
}


共2页: 上一页 1 [2] 下一页
相 关 文 章   发布商链接
·C#生成XML文件代码一例
·利用C#实现获得指定网页的源代码方法
·什么是抽象类?什么是接口?两者有什么...
·C#代码,Delphi和js脚本写的模拟显示...
·C#以度°分′秒″格式实现经纬度加减...
·最为经典的C#操作文件的方法大全
·C#实现把多个文件写入到一个文件中去...
·C#实现密码修改及其正则验证的代码
·C#实现合并多个结构一样的Excel代码
·C#实现读取sql2005日志的代码
 §最新评论:(评论内容只代表网友观点,与本站立场无关!)
网名: 验证码:  【所有评论】【↑返回顶部
评 分: 12 345
评论内容:(不能超过500字,请自觉遵守互联网相关政策法规。[按 Ctrl+Enter 可直接提交]
注意:请勿在本站发布政治话题、色情及违反法律的内容。
IT知道网 声明:刊登此文章是为了传递更多信息,文章内容仅供参考,转载请注明出处。
推 荐 文 章
·最为经典的C#操作文件的方法...
·有助快速理解C#委托和事件之...
·C#泛型学习笔记总结
·c#语言从dbf数据库提取数据并
·C#编写控制线程的运行和线程...
·怎样在C#中删除只读文件及其...
·C#函数中返回多个值的两种方...
·如何在C#中插入照片到Excel文
·如何在c#中获取事件注册的方...
·C#对timer类的使用操作代码
·什么是泛型?泛型的一些概述
·C#如何从文本文件读取信息并...
·如何在c#中去掉字符串中的回...
·如何使用C#获取IIS服务器版本...
·什么是泛型编程思想?及其简...
热 门 文 章
·C#如何获取文件路径中的文件...
·c#中收发邮件处理代码(POP3,...
·浅谈接口和抽象类的区别,加...
·什么是c#深拷贝与浅拷贝及其...
·C#语言实现创建、删除和移动...
·C#中关于四舍五入函数的讨论...
·c#中的ArrayList属性祥解及其...
·快速进行List排序的通用方法...
·C#对timer类的使用操作代码
·C#如何从文本文件读取信息并...
·C#语言实现从XML文件导出数据...
·用C#编写ActiveX控件代码实例
·如何在c#中去掉字符串中的回...
·String.Split 方法使用及其代...
·C#语言绘制实时曲线图代码实...
网站首页 - 关于本站 - 加入收藏 - 网站地图 - 友情连接 - 在线留言 - 联系我们 - 返回顶部
Copyright © 2007 IT知道网.[冀ICP备07026896号]. All Rights Reserved .