I wish to pass an image pointer from a C# program to a C++ program, then the C++ program to generate a cv::Mat
image and write the image to the disk to verify that it receives the correct image. However, I got an error of Read access violation
. Which part of my code is wrong?
I am referring to the code and has modified from here. Attached below is the main code:
Server.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);
Client.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);