Call DLL function - 'System.AccessViolationException'


  •  I have the following defined:

    In C#:

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

    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";

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

    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


All replies