Hello every one
I want to communicate with C++ program with my C#, that is data transfer between C++ and C# using shared memory , Here is my Implementation
I have 2 methods
CreateMemoryShare();
ReleaseMemoryShare();
both on writer and reader side
SafeFileMappingHandle hMapFile = null;
IntPtr pView;
[DllImport("Kernel32.dll", SetLastError = true)]
public static extern SafeFileMappingHandle CreateFileMapping(IntPtr hFile, IntPtr lpAttributes, FileProtection flProtect, uint dwMaximumSizeHigh, uint dwMaximumSizeLow, string lpName);
[DllImport("Kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr MapViewOfFile(SafeFileMappingHandle hFileMappingObject, FileMapAccess dwDesiredAccess, uint dwFileOffsetHigh, uint dwFileOffsetLow, uint dwNumberOfBytesToMap);
private void CreateMemoryShare()
{
hMapFile = NativeMethod.CreateFileMapping(INVALID_HANDLE_VALUE, IntPtr.Zero, FileProtection.PAGE_READWRITE, 0, MapSize, MapName);
pView = NativeMethod.MapViewOfFile(hMapFile, FileMapAccess.FILE_MAP_ALL_ACCESS, 0, ViewOffset, ViewSize);
}
private void ReleaseMemoryShare()
{
NativeMethod.UnmapViewOfFile(pView);
pView = IntPtr.Zero;
hMapFile.Close();
hMapFile = null;
}
At the Write/Sender side
OpenFileDialog objOpenFile = new OpenFileDialog();
objOpenFile.ShowDialog();
FileStream fs = new FileStream(objOpenFile.FileName, FileMode.Open);
BinaryReader objBinaryReader = new BinaryReader(fs);
byte[] ImageBuffer = new byte[fs.Length];
objBinaryReader.Read(ImageBuffer, 0, ImageBuffer.Length);
objBinaryReader.Close();
fs.Close();
CreateMemoryShare();
Marshal.Copy(ImageBuffer, 0, pView, ImageBuffer.Length);
Thread.Sleep(10000);
ReleaseMemoryShare();
at the reader/receive side
CreateMemoryShare();
byte[] ReceivedByte = new byte[100000000];
Marshal.Copy(pView, ReceivedByte, 0, ReceivedByte.Length);
ReleaseMemoryShare();
Code is working fine but here the byte array ReceivedByte is fixed to 100000000 bytes but for some cases while communication the data will be just 1000 of any string data which will be of lesser size.For less data the length that I have given for ReceivedByte is too large.
So how to get the length of data that has been written in memory so that i can dynamically modify the ReceivedByte size.
Tried to get the length using
Marshal.SizeOf(pView);
but it shows only 4 -16 which is not actual data.
Can any one guide or suggest how to get the size of data written inside the memory location.
Advance thanks.