none
Call DLL function - 'System.AccessViolationException'

    Question

  •  I have the following defined:

    In C#:

    [DllImport("mt2bs.dll", EntryPoint = "SendText")]
    public static extern bool SendText();

    public
    partial class Form1 : Form
    {
    ...
        private void button2_Click(object sender, EventArgs e)
        {
            bool b = mt2bsdll.SendText();
            textBox1.Text = b.ToString();
        }
    }


    In the C++ DLL Code:

    const int VIEW_SIZE=50;
    __declspec(dllexport) bool __stdcall SendText()
    {
        HANDLE m_hFileMapping = OpenFileMapping (FILE_MAP_READ,
    false, "MyFileMapping\0");
        
    if (m_hFileMapping == NULL) return false;
        void *pSharedBuffer = MapViewOfFile (m_hFileMapping, FILE_MAP_READ, 0, 0, VIEW_SIZE);
        
    HANDLE hMutex = OpenMutex (SYNCHRONIZE, false, "MyMutex\0");
        
    if (hMutex == NULL) return false;
        HANDLE hEvent = OpenEvent (SYNCHRONIZE,
    false, "MyEvent\0");
        
    if (hEvent == NULL) return false;

        WaitForSingleObject(hMutex, INFINITE);
        char* text2="test string";

        CopyMemory((
    char*) pSharedBuffer,text2, VIEW_SIZE);    // error 'System.AccessViolationException' 
        // CopyMemory(text,(char*) pSharedBuffer,VIEW_SIZE);    // it work!

        ReleaseMutex(hMutex);
        PulseEvent(hEvent);    
        
        
    return true;
    }

    This all compiles and runs but when the function returns I get a:
    An unhandled exception of type 'System.AccessViolationException'

    What am I doing wrong?

    Sunday, July 06, 2008 3:33 PM

Answers

All replies

  • This is a quick guess, but since you've used FILE_MAP_READ for access, you won't be able to write to that memory.
    http://blog.voidnish.com
    Sunday, July 06, 2008 3:45 PM
    Moderator
  • i changed:
    void
    *pSharedBuffer = MapViewOfFile (m_hFileMapping, FILE_MAP_WRITE, 0, 0, VIEW_SIZE);

    but the same result
    Sunday, July 06, 2008 3:59 PM
  •  ...Thanku!
    All works!
    Sunday, July 06, 2008 4:03 PM
  • What did you change for it to work?
    http://blog.voidnish.com
    Sunday, July 06, 2008 4:08 PM
    Moderator
  •  HANDLE m_hFileMapping = OpenFileMapping (FILE_MAP_WRITE, false, "MyFileMapping\0");
    void *pSharedBuffer = MapViewOfFile (m_hFileMapping, FILE_MAP_WRITE, 0, 0, VIEW_SIZE);

    ...I was inattentive.
    Sunday, July 06, 2008 4:11 PM
  • Ok - thanks. I just wanted to confirm that that were so before marking this as answered.
    http://blog.voidnish.com
    Sunday, July 06, 2008 4:13 PM
    Moderator