Solved

MemoryMappedFile Issue C#/C++

Posted on 2007-04-05
6
968 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:Kdo
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
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

 

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:Kdo
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

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

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

Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
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…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

832 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