Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2647048
  • 博文数量: 416
  • 博客积分: 10220
  • 博客等级: 上将
  • 技术积分: 4193
  • 用 户 组: 普通用户
  • 注册时间: 2006-12-15 09:47
文章分类

全部博文(416)

文章存档

2022年(1)

2021年(1)

2020年(1)

2019年(5)

2018年(7)

2017年(6)

2016年(7)

2015年(11)

2014年(1)

2012年(5)

2011年(7)

2010年(35)

2009年(64)

2008年(48)

2007年(177)

2006年(40)

我的朋友

分类: C/C++

2010-01-26 15:38:14


环境和的是xp, unicode
[0]
HANDLE WINAPI CreateFileMappingW(
  __in      HANDLE hFile,
  __in_opt  LPSECURITY_ATTRIBUTES lpAttributes,
  __in      DWORD flProtect,
  __in      DWORD dwMaximumSizeHigh,
  __in      DWORD dwMaximumSizeLow,
  __in_opt  LPCWSTR lpName
);
[0]
[1]
QSharedMemory *structMemory = new QSharedMemory(QString("TestFileMap"));
  bool bAttacth = structMemory->isAttached();
  bAttacth = structMemory->attach();
[1]  

由于[0]CreateFileMappingW的共享名称直接用的是其参数名lpName,而[2]structMemory->attach()用的key名称是
QString safeKey = makePlatformSafeKey(key);(参考qt源代码qsharedmemory_win.cpp中的QSharedMemoryPrivate::handle())
因此需要将两者的name或key保持一致,要加上函数makePlatformSafeKey,修改后的参考如下

#include "dialog.h"
#include
#include
#include
#include
#include
LPWSTR AnsiToUnicode(LPCSTR lpcstr)   //参数lpcstr类型也可是char*
{
 LPWSTR Pwstr;
 int  i;
 i=MultiByteToWideChar(CP_ACP,0,lpcstr,-1,NULL,0);
 Pwstr=new WCHAR[i];
 MultiByteToWideChar(CP_ACP,0,lpcstr,-1,Pwstr,i);
 return (Pwstr);
}
QString makePlatformSafeKey(const QString &key)
{
 const QString prefix = QLatin1String("qipc_sharedmemory_");
 
 QString result = prefix;
 QString part1 = key;
 part1.replace(QRegExp(QLatin1String("[^A-Za-z]")), QString());
 result.append(part1);
 QByteArray hex = QCryptographicHash::hash(key.toUtf8(), QCryptographicHash::Sha1).toHex();
 result.append(QLatin1String(hex));
#ifdef Q_OS_WIN
 return result;
#else
 return QDir::tempPath() + QLatin1Char('/') + result;
#endif
}
/*!
  \class Dialog
  \brief This class is a simple example of how to use QSharedMemory.
  It is a simple dialog that presents a few buttons. To compile the
  example, run make in qt/examples/ipc. Then run the executable twice
  to create two processes running the dialog. In one of the processes,
  press the button to load an image into a shared memory segment, and
  then select an image file to load. Once the first process has loaded
  and displayed the image, in the second process, press the button to
  read the same image from shared memory. The second process displays
  the same image loaded from its new loaction in shared memory.
*/
/*!
  The class contains a data member \l {QSharedMemory} {sharedMemory},
  which is initialized with the key "QSharedMemoryExample" to force
  all instances of Dialog to access the same shared memory segment.
  The constructor also connects the clicked() signal from each of the
  three dialog buttons to the slot function appropriate for handling
  each button.
*/
//! [0]
Dialog::Dialog(QWidget *parent)
  : QDialog(parent), sharedMemory("QSharedMemoryExample")
{
 m_structMemory = new QSharedMemory();
    ui.setupUi(this);
    connect(ui.loadFromFileButton, SIGNAL(clicked()), SLOT(loadFromFile()));
    connect(ui.loadFromSharedMemoryButton,
     SIGNAL(clicked()),
     SLOT(loadFromMemory()));
    setWindowTitle(tr("SharedMemory Example"));
}
//! [0]
/*!
  This slot function is called when the \tt {Load Image From File...}
  button is pressed on the firs Dialog process. First, it tests
  whether the process is already connected to a shared memory segment
  and, if so, detaches from that segment. This ensures that we always
  start the example from the beginning if we run it multiple times
  with the same two Dialog processes. After detaching from an existing
  shared memory segment, the user is prompted to select an image file.
  The selected file is loaded into a QImage. The QImage is displayed
  in the Dialog and streamed into a QBuffer with a QDataStream.
  Next, it gets a new shared memory segment from the system big enough
  to hold the image data in the QBuffer, and it locks the segment to
  prevent the second Dialog process from accessing it. Then it copies
  the image from the QBuffer into the shared memory segment. Finally,
  it unlocks the shared memory segment so the second Dialog process
  can access it.
  After this function runs, the user is expected to press the \tt
  {Load Image from Shared Memory} button on the second Dialog process.
  \sa loadFromMemory()
 */
//! [1]
void Dialog::loadFromFile()
{
 FileMapping();
 FileMapping();
 CreateFileMappingEx();
 
 
/************************************************/
 if (sharedMemory.isAttached())
  detach();
    ui.label->setText(tr("Select an image file"));
    QString fileName = QFileDialog::getOpenFileName(0, QString(), QString(),
                                        tr("Images (*.png *.xpm *.jpg)"));
    QImage image;
    if (!image.load(fileName)) {
        ui.label->setText(tr("Selected file is not an image, please select another."));
        return;
    }
    ui.label->setPixmap(QPixmap::fromImage(image));
//! [1] //! [2]
    // load into shared memory
    QBuffer buffer;
    buffer.open(QBuffer::ReadWrite);
    QDataStream out(&buffer);
    out << image;
    int size = buffer.size();
    if (!sharedMemory.create(size)) {
        ui.label->setText(tr("Unable to create shared memory segment."));
        return;
    }
    sharedMemory.lock();
    char *to = (char*)sharedMemory.data();
    const char *from = buffer.data().data();
    memcpy(to, from, qMin(sharedMemory.size(), size));
    sharedMemory.unlock();
}
//! [2]
/*!
  This slot function is called in the second Dialog process, when the
  user presses the \tt {Load Image from Shared Memory} button. First,
  it attaches the process to the shared memory segment created by the
  first Dialog process. Then it locks the segment for exclusive
  access, copies the image data from the segment into a QBuffer, and
  streams the QBuffer into a QImage. Then it unlocks the shared memory
  segment, detaches from it, and finally displays the QImage in the
  Dialog.
  \sa loadFromFile()
 */
//! [3]
void Dialog::loadFromMemory()
{
 if (!sharedMemory.attach()) {
  qDebug() << "Error = " << sharedMemory.errorString();
        ui.label->setText(tr("Unable to attach to shared memory segment.\n" \
        "Load an image first."));
        return;
    }
    QBuffer buffer;
    QDataStream in(&buffer);
    QImage image;
 ui.label->setPixmap(QPixmap::fromImage(image));
    sharedMemory.lock();
    buffer.setData((char*)sharedMemory.constData(), sharedMemory.size());
    buffer.open(QBuffer::ReadOnly);
    in >> image;
    sharedMemory.unlock();
    sharedMemory.detach();
    //ui.label->setPixmap(QPixmap::fromImage(image));
}
//! [3]
/*!
  This private function is called by the destructor to detach the
  process from its shared memory segment. When the last process
  detaches from a shared memory segment, the system releases the
  shared memory.
 */
void Dialog::detach()
{
    if (!sharedMemory.detach())
        ui.label->setText(tr("Unable to detach from shared memory."));
}
void Dialog::FileMapping(void)
{
 //打开共享的文件对象。
 LPCWSTR strText = AnsiToUnicode(makePlatformSafeKey("TestFileMap").toStdString().c_str());
 m_hMapFile = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, strText);
 if (m_hMapFile)
 {
  //显示共享的文件数据。
  HANDLE lpMapAddr = (LPTSTR)MapViewOfFile(m_hMapFile,FILE_MAP_WRITE|FILE_MAP_READ, 0,0,0);
  ShareStruct *mm = (ShareStruct *)lpMapAddr;
  qDebug() << "map end" << mm->a;
  //UnmapViewOfFile(lpMapAddr);
  //qDebug() << "map end";
 }
 else
 {
  //创建共享文件。
  m_hMapFile = CreateFileMapping( (HANDLE)0xFFFFFFFF,NULL, PAGE_READWRITE,0,1024, strText);
  //拷贝数据到共享文件里。
  LPVOID lpMapAddr = (HANDLE)MapViewOfFile(m_hMapFile,FILE_MAP_ALL_ACCESS, 0,0,0);
  std::wstring strTest= QString("TestFileData").toStdWString();
  //wcscpy(m_shareStruct.a, strTest.c_str());               
  m_shareStruct = (ShareStruct *)lpMapAddr;
  strcpy(m_shareStruct->a,  "TestFileData");               
  m_shareStruct->i = 1;               
  FlushViewOfFile(lpMapAddr,strTest.length()+1);
  QSharedMemory *structMemory = new QSharedMemory(QString("TestFileMap"));
  bool bAttacth = structMemory->isAttached();
  bAttacth = structMemory->attach();
  qDebug() << structMemory->errorString();
  //bool bRet = m_structMemory->create(sizeof(ShareStruct) ); 
  if (bAttacth)
  {
   ShareStruct *ss = (ShareStruct *)structMemory->data();
   qDebug() << ss->a;
  }
 }
}
void Dialog::CreateFileMappingEx()
{
 DWORD timebegin = ::timeGetTime();
 HANDLE fp = CreateFile(TEXT("E:/svn-build.rar"),//这里输入需要复制的文件 src
  GENERIC_READ | GENERIC_WRITE,
  FILE_SHARE_READ,
  NULL,
  OPEN_EXISTING,
  FILE_FLAG_SEQUENTIAL_SCAN,
  NULL);
 if(fp == NULL)
 {
  qDebug()<<"错误"<  return;
 }
 DWORD dwBytesInBlock = GetFileSize(fp,NULL); //文件长度
 // 创建文件映射内核对象,句柄保存于hFileMapping
 HANDLE hFileMapping = CreateFileMapping(fp,
  NULL,
  PAGE_READWRITE,
  0,//(DWORD)(dwBytesInBlock >> 16),
  dwBytesInBlock,//(DWORD)(dwBytesInBlock & 0x0000FFFF),
  NULL);
 int dwError = GetLastError();
 // 释放文件内核对象
 CloseHandle(fp);
 // 偏移地址
 __int64 qwFileOffset = 0;
 // 将文件数据映射到进程的地址空间
 LPVOID pbFile = (LPVOID)MapViewOfFile( hFileMapping,
  FILE_MAP_ALL_ACCESS,
  (DWORD)(qwFileOffset >> 32),
  (DWORD)(qwFileOffset & 0xFFFFFFFF),
  dwBytesInBlock);
 HANDLE wp = CreateFile( TEXT("E:/仙剑5.rar"),//这里输入 需要粘贴的文件 dst
  GENERIC_READ | GENERIC_WRITE,
  FILE_SHARE_WRITE,
  NULL,
  CREATE_ALWAYS,
  FILE_FLAG_SEQUENTIAL_SCAN | FILE_FLAG_WRITE_THROUGH,
  NULL);
 HANDLE hFileMapping2 = CreateFileMapping( wp,
  NULL,
  PAGE_READWRITE,
  0,//(DWORD)(dwBytesInBlock >> 16),
  dwBytesInBlock,//(DWORD)(dwBytesInBlock & 0x0000FFFF),
  NULL);

 CloseHandle(wp);
 LPVOID pbFile2 = (LPVOID)MapViewOfFile( hFileMapping2,
  FILE_MAP_ALL_ACCESS,
  (DWORD)(qwFileOffset >> 32),
  (DWORD)(qwFileOffset & 0xFFFFFFFF),
  dwBytesInBlock);
 memcpy(pbFile2,pbFile,dwBytesInBlock);
 UnmapViewOfFile(pbFile2);
 UnmapViewOfFile(pbFile);
 CloseHandle(hFileMapping2);
 CloseHandle(hFileMapping);
 DWORD timeend = ::timeGetTime();
 qDebug()<<"CreateFileMapping和MapViewOfFile程序运行时间为"<}
 
阅读(9929) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~