码迷,mamicode.com
首页 > 编程语言 > 详细

c++共享内存(转载)

时间:2016-06-30 12:31:26      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:

对于连个不同的进程之间的通信,共享内存是一种比较好的方式,一个进程把数据发送到共享内存中,

另一个进程可以读取改数据,简单记录一下代码

 

 1 #define BUF_SIZE 256
 2 TCHAR szName[]=TEXT("Global\\YourFileMappingObject");    //指向同一块共享内存的名字
 3 
 4 int SetFileName(LPCTSTR str)
 5 {
 6     HANDLE hMapFile;
 7     LPCTSTR pBuf;
 8 
 9     hMapFile = CreateFileMapping(
10             INVALID_HANDLE_VALUE,    // use paging file
11             NULL,                    // default security
12             PAGE_READWRITE,          // read/write access
13             0,                       // maximum object size (high-order DWORD)
14             BUF_SIZE,                // maximum object size (low-order DWORD)
15             szName);                 // name of mapping object
16 
17     if (hMapFile == NULL)
18     {
19         _tprintf(TEXT("Could not create file mapping object (%d).\n"),
20         GetLastError());
21         return 0;
22     }
23     pBuf = (LPTSTR) MapViewOfFile(hMapFile,   // handle to map object
24             FILE_MAP_ALL_ACCESS, // read/write permission
25             0,
26             0,
27             BUF_SIZE);
28 
29     if (pBuf == NULL)
30     {
31         _tprintf(TEXT("Could not map view of file (%d).\n"),
32         GetLastError());
33 
34         CloseHandle(hMapFile);
35 
36         return 0;
37     }
38 
39     memcpy((PVOID)pBuf, str, BUF_SIZE);
40     return 1;
41 }
42 
43 LPCTSTR GetBuffer()
44 {
45     HANDLE hMapFile;
46     LPCTSTR pBuf;
47 
48     hMapFile = CreateFileMapping(
49             INVALID_HANDLE_VALUE,    // use paging file
50             NULL,                    // default security
51             PAGE_READWRITE,          // read/write access
52             0,                       // maximum object size (high-order DWORD)
53             BUF_SIZE,                // maximum object size (low-order DWORD)
54             szName);                 // name of mapping object
55 
56     if (hMapFile == NULL)
57     {
58         _tprintf(TEXT("Could not create file mapping object (%d).\n"),
59             GetLastError());
60         return NULL;
61     }
62     pBuf = (LPTSTR) MapViewOfFile(hMapFile,   // handle to map object
63             FILE_MAP_ALL_ACCESS, // read/write permission
64             0,
65             0,
66             BUF_SIZE);
67 
68     if (pBuf == NULL)
69     {
70         _tprintf(TEXT("Could not map view of file (%d).\n"),
71                 GetLastError());
72 
73         CloseHandle(hMapFile);
74         return NULL;
75     }
76     return pBuf;
77 }

 

c++共享内存(转载)

标签:

原文地址:http://www.cnblogs.com/george-cw/p/5629241.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!