- 注册时间
- 2022-8-23
- 最后登录
- 2024-3-6
- 在线时间
- 2 小时
编程入门
- 天马币
- 28
|
共享内存通信演示
vc6.0 c++
演示步骤:
1. 启动smserver
2. <创建共享内存>
3. 启动smclient
4. 在smserver中,输入要写入的内容,然后点击“写入数据”
5. 在smclient可以看到smserver中写入的数据
smserver端可以反复写入数据,则在smclient端会可见随着改变
此演示非常简单,只是演示如何使用,没有考虑性能、方式等,如果需要拿到真正的代码中使用,则需要考虑其它额外的工作,比如方式、效率等
创建内存- void CSmserverDlg::OnBtnopensm()
- {
- // TODO: Add your control notification handler code here
- if ( m_hShareMem == NULL )
- {
- SECURITY_ATTRIBUTES sa;
- memset( &sa, 0, sizeof(sa) );
- sa.nLength = sizeof(sa);
- m_hShareMem = CreateFileMapping( (HANDLE)0xFFFFFFFF, &sa, PAGE_READWRITE, 0, m_dwSMLen, TEXT("rm_test_share_memory_trans_20100601") );
- if ( m_hShareMem == NULL )
- {
- m_StStatus.SetWindowText( TEXT("创建共享内存失败!") );
- }
- else
- {
- m_lpVoidSM = MapViewOfFile( m_hShareMem, FILE_MAP_ALL_ACCESS, 0, 0, 0 );
- if ( m_lpVoidSM == NULL )
- {
- CString strErr;
- strErr.Format( TEXT("创建共享内存地址失败!error = %d"), GetLastError() );
- m_StStatus.SetWindowText( strErr );
- CloseHandle( m_hShareMem );
- m_hShareMem = NULL;
- }
- else
- {
- m_StStatus.SetWindowText( TEXT("创建共享内存成功---") );
- // 清空第一个字节
- memcpy( m_lpVoidSM, TEXT("\0"), 1 );
- }
- }
- }
- }
- 写入数据
- void CSmserverDlg::OnBtnwrite()
- {
- // TODO: Add your control notification handler code here
- if ( m_lpVoidSM == NULL )
- {
- AfxMessageBox( TEXT("先创建共享内存!"), MB_ICONSTOP );
- return;
- }
- CString strText;
- m_EdWrite.GetWindowText( strText );
- if ( strText.GetLength() == 0 )
- {
- AfxMessageBox( TEXT("必需输入要写入的内容!"), MB_ICONSTOP );
- return;
- }
- strcpy( (char*)m_lpVoidSM, strText.GetBuffer(0) );
- }
- 另一个EXE-读取数据。。。如下
- void CSmclientDlg::OnBtnopensm()
- {
- // TODO: Add your control notification handler code here
- if ( m_hShareMem == NULL )
- {
- SECURITY_ATTRIBUTES sa;
- memset( &sa, 0, sizeof(sa) );
- sa.nLength = sizeof(sa);
- m_hShareMem = CreateFileMapping( (HANDLE)0xFFFFFFFF, &sa, PAGE_READWRITE, 0, m_dwSMLen, TEXT("rm_test_share_memory_trans_20100601") );
- if ( m_hShareMem == NULL )
- {
- AfxMessageBox( TEXT("打开共享内存失败!"), MB_ICONSTOP );
- }
- else
- {
- m_lpVoidSM = MapViewOfFile( m_hShareMem, FILE_MAP_ALL_ACCESS, 0, 0, 0 );
- if ( m_lpVoidSM == NULL )
- {
- AfxMessageBox( TEXT("打开共享内存地址失败!"), MB_ICONSTOP );
- CloseHandle( m_hShareMem );
- m_hShareMem = NULL;
- }
- else
- {
- SetTimer( 1, 100, NULL );
- m_BtnOpenSM.SetWindowText( TEXT("正在监视...") );
- m_BtnOpenSM.EnableWindow( FALSE );
- }
- }
- }
- }
- void CSmclientDlg::OnTimer(UINT nIDEvent)
- {
- // TODO: Add your message handler code here and/or call default
- if ( strlen((char*)m_lpVoidSM) > 0 )
- {
- m_StRead.SetWindowText( (char*)m_lpVoidSM );
- memcpy( m_lpVoidSM, TEXT("\0"), 1 );
- }
- CDialog::OnTimer(nIDEvent);
- }
复制代码
|
|