共享内存与内存映射文件

时间:2016-04-15 02:41:35

标签: c# c++ memory-management shared-memory memory-mapped-files

我正在创建两个应用程序:一个在C#中,一个在C ++中,我想在两个应用程序之间使用共享内存用于IPC。对于共享内存,我使用了Memory-Mapped File。

C#app将创建MemoryMappedFile并向其写入数据:

using System;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Threading;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            using (MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen("testmap", 256))
            {
                using (MemoryMappedViewStream stream = mmf.CreateViewStream())
                {
                    BinaryWriter writer = new BinaryWriter(stream);
                    writer.Write("Hello, world!");
                }
            }

            Console.ReadKey();
        }
    }
}

然后,C ++应用程序将从共享内存中读取值:

#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <tchar.h>
#pragma comment(lib, "user32.lib")

#define BUF_SIZE 256
TCHAR szName[] = TEXT("testmap");

int _tmain()
{
    HANDLE hMapFile;
    LPCTSTR pBuf;

    hMapFile = OpenFileMapping(
        FILE_MAP_ALL_ACCESS,   // read/write access
        FALSE,                 // do not inherit the name
        szName);               // name of mapping object

    if (hMapFile == NULL)
    {
        _tprintf(TEXT("Could not open file mapping object (%d).\n"),
            GetLastError());
        return 1;
    }

    pBuf = (LPTSTR)MapViewOfFile(hMapFile, // handle to map object
        FILE_MAP_ALL_ACCESS,  // read/write permission
        0,
        0,
        BUF_SIZE);

    if (pBuf == NULL)
    {
        _tprintf(TEXT("Could not map view of file (%d).\n"),
            GetLastError());

        CloseHandle(hMapFile);

        return 1;
    }

    MessageBox(NULL, pBuf, TEXT("Process2"), MB_OK);

    UnmapViewOfFile(pBuf);

    CloseHandle(hMapFile);

    return 0;
}

首先,我将运行C#app创建共享内存,然后运行C ++ app从共享内存中读取数据。但我在C ++应用程序中遇到异常:“无法打开文件映射对象(2)”。是因为.net中的内存映射文件与我在这里使用的C ++内存映射文件不兼容吗?如果是这样,我可以使用任何库来共享C ++和C#应用程序之间的内存吗?或者我在代码中的哪个地方犯了错误?

Upadted:

这是我的C#代码中的一个错误,Console.ReadKey()应该在using块中!感谢Severin。

0 个答案:

没有答案
相关问题