簡體   English   中英

通過共享 memory 在 C# 和 C++ 之間傳遞圖像指針

[英]Pass image pointer via shared memory between C# and C++

我希望將 C# 程序中的圖像指針傳遞給 C++ 程序,然后 C++ 程序生成一個cv::Mat圖像並將圖像寫入磁盤以驗證該圖像是否正確。 但是,我收到了Read access violation的錯誤。 我的代碼的哪一部分是錯誤的?

我指的是代碼並已從此處修改。 下面附上主要代碼:

服務器.cs

const uint BUFFER_SIZE = 1024;
string strMapFileName = "SharedMemory_CPP_CSHARP";
IntPtr pBuf;
IntPtr hMapFile;

hMapFile = FileMappingNative.CreateFileMapping(
    (IntPtr)FileMappingNative.INVALID_HANDLE_VALUE, IntPtr.Zero, 
    FileProtection.PAGE_READWRITE, 0, BUFFER_SIZE, strMapFileName);
pBuf = FileMappingNative.MapViewOfFile(
    hMapFile, FileMapAccess.FILE_MAP_ALL_ACCESS, 0, 0, BUFFER_SIZE);

System.Drawing.Bitmap bm = new System.Drawing.Bitmap("<imagePath>/image.jpg");
System.Drawing.Imaging.BitmapData bmpData = bm.LockBits(
    new System.Drawing.Rectangle(0, 0, bm.Width, bm.Height),
        System.Drawing.Imaging.ImageLockMode.ReadWrite,
        System.Drawing.Imaging.PixelFormat.Format24bppRgb);
Marshal.Copy(new IntPtr[] { bmpData.Scan0 }, 0, pBuf, 1);

客戶端.cpp

#define BUF_SIZE 1024
TCHAR szName[] = TEXT("SharedMemory_CPP_CSHARP");
HANDLE hMapFile;
char* pBuf;

hMapFile = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, szName);
pBuf = (char*)MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, BUF_SIZE);

wchar_t pstrDest[BUF_SIZE];
int len = mblen(NULL, MB_CUR_MAX);
int nLen = len * strlen(pBuf);
mbtowc(pstrDest, pBuf, nLen + 1);
cv::Mat buf = cv::Mat(100, 100, CV_8UC1, pstrDest);
cv::imwrite("<iamgePath>/image1.jpg", buf);

我不知道為什么要手動從Bitmap中復制位,也不知道為什么要使用 PInvoke 創建內存映射文件,因為這兩種方法都容易出現許多錯誤。

例如,您可能會遇到訪問沖突,因為您將緩沖區指針發送到 MM 文件,而不是實際數據,並且您在 C++ 端讀取它的方式看起來也很可疑。 在許多地方還存在 memory 泄漏。

您可以使用MemoryMappedFileBitmap.Save更簡單地做到這一點。

const uint BUFFER_SIZE = 1024;   // sounds a bit small
string strMapFileName = "SharedMemory_CPP_CSHARP";

using (var bm = new System.Drawing.Bitmap("<imagePath>/image.jpg"))
using (var file = MemoryMappedFile.CreateOrOpen(strMapFileName, BUFFER_SIZE, MemoryMappedFileAcces.ReadWrite))
using (var stream = file.CreateViewStream())
{
    bm.Save(stream, ImageFormat.Png);
}

暫無
暫無

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

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