Solved

MemoryMappedFile Issue C#/C++

Posted on 2007-04-05
6
987 Views
Last Modified: 2013-11-07
I have a Memory Mapped File that is being populated by a seperate C++ application and I am reading the contents of that file using a C# Windows Application.  Everything works fine from the perspective of opening the file and view, retrieving the data and working with the resultant byte array.
However, I need to zero-out the memory when I am done and I cannot get that to work.  When I call the ZeroMemory Kernel Method, I keep getting the following:

System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

Here the DLL Import signature:

[DllImport("kernel32", SetLastError = true)]
public static extern void ZeroMemory(IntPtr dest, int size);

Can somebody please help?
0
Comment
Question by:ktola
  • 3
  • 2
6 Comments
 
LVL 45

Expert Comment

by:Kent Olsen
ID: 18861712
Hi ktola,

Just to be sure, the first parameter to ZeroMemory is a pointer to void.  (Or have you overloaded the function?)

Also, you need to call ZeroMemory before closing the file or unmapping the region.


Kent
0
 

Author Comment

by:ktola
ID: 18861737
I implemented IDisposable in my MemoryMappedFile class - here is the overloaded Dispose method that is called:

protected virtual void Dispose(bool disposing, int MemorySize)
{
     if (IsOpen)
     {
          if (MemorySize > 0)
               Win32MapApis.ZeroMemory(_hMap, MemorySize);
          Win32MapApis.UnmapViewOfFile(_hMap);
          Win32MapApis.CloseHandle(_hMap);
     }
     _hMap = NULL_HANDLE;

     if (disposing)
          GC.SuppressFinalize(this);
}

_hMap is the pointer to the file mapping created with this call:

map._hMap = Win32MapApis.CreateFileMapping(hFile, IntPtr.Zero, (int)protection, (int)((maxSize >> 32) & 0xFFFFFFFF), (int)(maxSize & 0xFFFFFFFF), name);

I have not overloaded anything at this point.  Finally, here is the main method call:

                    map = MemoryMappedFile.Open(MapAccess.FileMapAllAccess, mappedFileName);
                    if (map._hMap != MemoryMappedFile.NULL_HANDLE)
                    {
                        using (Stream dataMem = map.MapView(MapAccess.FileMapAllAccess, 0, maxBytes))
                        {
                            if (dataMem.Length > 0)
                            {
                                dataBytes = new byte[dataMem.Length];
                                dataMem.Read(dataBytes, 0, dataBytes.Length);
                                dataValues = Encoding.Unicode.GetString(dataBytes).Trim();
                                if (dataValues.Length > 0)
                                {
                                    memSize = sizeof(char) * dataValues.Length;
                                    //Do Work
                                }
                                else
                                    memSize = 0;
                                dataMem.Close();
                            }
                        }
                        map.Dispose(true, memSize);
0
 
LVL 48

Accepted Solution

by:
AlexFM earned 500 total points
ID: 18862475
hMap is not pointer, this is handle to memory mapped file. Pointer is returned by MapViewOfFile API. I think that this is map.MapView in your code. Any direct access to memory should be done with value returned by MapViewOfFile and not with value returned by CreateFileMapping.
Anyway, there is no need to zero memory before closing, you can remove this line.
0
MIM Survival Guide for Service Desk Managers

Major incidents can send mastered service desk processes into disorder. Systems and tools produce the data needed to resolve these incidents, but your challenge is getting that information to the right people fast. Check out the Survival Guide and begin bringing order to chaos.

 

Author Comment

by:ktola
ID: 18883021
Unfortunately, I need to zero the memory as the C++ application on the other side is looking for the memory to be zeroed out so it knows I have cleared the data.  It then fills the file with new data.
0
 
LVL 45

Expert Comment

by:Kent Olsen
ID: 18883237
That's fine.

As Alex pointed out, you need to zero the memory starting at a memory address, not the value of the file handle.


Kent
0
 

Author Comment

by:ktola
ID: 19049875
Thank you for all of your help.  I ended up scrapping the entire concept and, instead, building a port-level queue to handle the traffic in C++.  That queue exposed an interface for .NET and that seemed to suffice.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Generate Unique ID in VB.NET 21 99
I need help adding validation to my MVC.Net view 6 21
WPF Select Items 3 24
Header Font Size in Grid View 6 22
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

679 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question