簡體   English   中英

使用 Memory 映射文件 (IOException) 的進程間通信(C++ 到 C#)

[英]Inter-process communication (C++ to C#) using Memory mapped file (IOException)

有兩個進程:一個寫在C++,一個寫在C#。

簡單的說,C++進程會創建一個文件名為“test.dat”,map這個文件給它的memory,然后一直寫就可以了。

另一方面,只要 memory 發生變化,C# 進程就會打開文件並讀取。

問題是在 C# 端,它不讓我打開文件。 (IOException 表示另一個進程正在使用中”

這是我測試過的。

//C++
// Test create & open
void CTestDlg::OnBnClickedBtn1()
{
    WCHAR wcsDebug[1024];
    HANDLE hFile, hMapFile;

    UINT size = sizeof(syncData);

    hFile = CreateFile(L"C:\\Users\\test\\Documents\\2134\\test.dat", GENERIC_READ | GENERIC_WRITE,
        FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

    if (hFile != INVALID_HANDLE_VALUE)
    {
        hMapFile = CreateFileMapping(hFile, NULL, PAGE_READWRITE, 0, size, NULL);

        if (hMapFile)
        {
            g_pb = (BYTE*)MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, 0);
        }
    }
}

// Test Writing 
void CLibTestDlg::OnBnClickedBtn2()
{
    WCHAR sz[] = L"C:\\Users\\test\\Documents\\2134\\";
    WCHAR wcsFilePath[MAX_PATH];

    CString str;
    GetDlgItemText(IDC_EDIT_FID, str);


    if (str != L"\0")
    {
        swprintf_s(wcsFilePath, _countof(wcsFilePath), L"%s%s", sz, str.GetBuffer());

        if (g_pb)
        {
            syncData sd;

            sd.dwCurrent = nCurr;
            sd.dwTotal = 15;
            sd.eSyncType = TYPE_DOWNLOAD;

            StringCchCopy(sd.wcsFileName, _countof(sd.wcsFileName), wcsFilePath);
            sd.eReqType = TYPE_DOWNLOAD;
            sd.ullTimeStamp = GetTickCount();

            nCurr++;

            memcpy(g_pb, &sd, sizeof(sd));
        }
    }
}

C# 以下部分:

        private void Button_MouseUp(object sender, RoutedEventArgs e)
        {
            Console.WriteLine("Click");

            FileStream fs = File.Open(@"C:\\Users\\test\\Documents\\2134\\test.dat", FileMode.Open, FileAccess.ReadWrite); // Error Here! IOException: The file is being used by another process.

            using (var mmf = MemoryMappedFile.CreateFromFile(fs, "mmf", 0, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true))
            {
                using (var accessor = mmf.CreateViewAccessor(0, 544))
                {
                    DWORD dwCurrent;
                    accessor.Read(0, out dwCurrent);

                    Console.WriteLine("Hello" + dwCurrent);
                }
            }
        }

關於處理兩個進程之間的文件共享的任何想法?

FileStream 默認僅允許讀取共享,這與您打開 c++ 文件的方式不兼容。 您也需要請求寫入共享:

File.Open(@"...", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM