callback 函數中訪問類成員變數

來源:互聯網
上載者:User

如何在callback 函數中訪問類的成員變數,今天遇到了這個問題,半天才解決,

由於callback函數必須為static函數,而static函數 不能訪問非static變數

其實很簡單,只需要聲明一個類的指標,將指標指向該類,並將該指標傳入callback函數即可以對該類中的任何成員進行操作了

 

例如 

class CGPS_zzDlg : public CDialog
{
// Construction
public:
 CGPS_zzDlg(CWnd* pParent = NULL); // standard constructor

// Dialog Data
 //{{AFX_DATA(CGPS_zzDlg)
 enum { IDD = IDD_GPS_ZZ_DIALOG };
 CButton m_ButOpen;
 CButton m_ButClose;
 CString m_time;
 CString m_lati;
 CString m_longi;
 //}}AFX_DATA

 // ClassWizard generated virtual function overrides
 //{{AFX_VIRTUAL(CGPS_zzDlg)
 protected:
 virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
 //}}AFX_VIRTUAL

// Implementation
protected:
 HICON m_hIcon;

 // Generated message map functions
 //{{AFX_MSG(CGPS_zzDlg)
 virtual BOOL OnInitDialog();
 afx_msg void OnBtnOpencom();
 afx_msg void OnBtnClosecom();
 //}}AFX_MSG
 DECLARE_MESSAGE_MAP()
 DCB dcb;      /* 串口參數結構體 */
 HANDLE m_hComm;     /* 串口操作控制代碼 */
 HANDLE m_ExitThreadEvent;  /* 串口接收線程退出事件 */
 CString m_strRecDisp;   /* 接收區顯示字元 */
 
 BOOL ClosePort(void);   /* 關閉串口 */

 // 開啟串口
 BOOL OpenPort(LPCTSTR Port, int BaudRate, int DataBits, int StopBits, int Parity);

 // 串口接收線程
 static DWORD CommRecvTread(LPVOID lparam);

 // 串口接收資料成功回呼函數
 typedef void (CALLBACK *ONCOMMRECV)(CWnd* pWnd, char *buf, int buflen);
 static void CALLBACK OnCommRecv(CWnd* pWnd, char *buf, int buflen );
 
};

只需在callback函數中聲明指向類的指標pDlg即可

 

void CALLBACK CGPSDlg::OnCommRecv(CWnd* pWnd, char *buf, int buflen )
{

    CGPSDlg * pDlg = (CGPS_zzDlg*)pWnd;

 

}

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.