Solved

MemoryMappedFile Issue C#/C++

Posted on 2007-04-05
6
978 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
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 

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

Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

Question has a verified solution.

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

Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…

809 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