Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. [SOLVED] System.AccessViolationException When Calling Dll Function Again

[SOLVED] System.AccessViolationException When Calling Dll Function Again

Scheduled Pinned Locked Moved C#
csharpperformancehelpquestion
9 Posts 7 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • D Offline
    D Offline
    Django_Untaken
    wrote on last edited by
    #1

    The problem was in the unmanaged DLL. But I really learnt a great deal about other topics such as BackgroundWorkers and TPL. Thanks all. ======================= Hello There. I have this small DLL that takes input_name and output_name as parameters. It opens the input file, reads it and produces output file with the specified name after some processing. I then call this function from C#. First time I call it, it runs fine. But second time around, it throws this exception An unhandled exception of System.AccessViolationException occured in CSharpProgram.exe. Attempted to read or write protected memory. Here is what I am trying.

    [DllImport("MyDll.dll", CallingConvention = CallingConvention.Cdecl)]
    public static extern int Call_Dll_Main(string input, string output);

    private void Button_Click(object sender, EventArgs ea)
    {
    new System.Threading.Thread(new System.Threading.ThreadStart(Call_Dll_Function)).Start()
    }

    private void Call_Dll_Function()
    {
    int nResult = Call_Dll_Main(txtInputFile.Text.Trim(), txtOutputFile.Text.Trim()); // HERE EXCEPTION COMES...FIRST TIME FINE...IT COMES SECOND TIME I CLICK THE BUTTON
    }

    What could be wrong? What am I missing here? Thanks for any input.

    D L S B M 6 Replies Last reply
    0
    • D Django_Untaken

      The problem was in the unmanaged DLL. But I really learnt a great deal about other topics such as BackgroundWorkers and TPL. Thanks all. ======================= Hello There. I have this small DLL that takes input_name and output_name as parameters. It opens the input file, reads it and produces output file with the specified name after some processing. I then call this function from C#. First time I call it, it runs fine. But second time around, it throws this exception An unhandled exception of System.AccessViolationException occured in CSharpProgram.exe. Attempted to read or write protected memory. Here is what I am trying.

      [DllImport("MyDll.dll", CallingConvention = CallingConvention.Cdecl)]
      public static extern int Call_Dll_Main(string input, string output);

      private void Button_Click(object sender, EventArgs ea)
      {
      new System.Threading.Thread(new System.Threading.ThreadStart(Call_Dll_Function)).Start()
      }

      private void Call_Dll_Function()
      {
      int nResult = Call_Dll_Main(txtInputFile.Text.Trim(), txtOutputFile.Text.Trim()); // HERE EXCEPTION COMES...FIRST TIME FINE...IT COMES SECOND TIME I CLICK THE BUTTON
      }

      What could be wrong? What am I missing here? Thanks for any input.

      D Offline
      D Offline
      Dave Kreskowiak
      wrote on last edited by
      #2

      Well, the first thing I would do is put those TextBox values you trim into variables before you pass them to the .DLL. The GC will collect those values since they don't have any managed variables or pins holding onto references to them so the GC may be collecting them before your DLL code is finished with them. Next, it would appear that you're completely ignoring the return code from the C function. I t has nothing to do with the error, but it's something to watch out for. Any other problems would be in the C code itself, which you didn't show for this function.

      A guide to posting questions on CodeProject

      Click this: Asking questions is a skill. Seriously, do it.
      Dave Kreskowiak

      1 Reply Last reply
      0
      • D Django_Untaken

        The problem was in the unmanaged DLL. But I really learnt a great deal about other topics such as BackgroundWorkers and TPL. Thanks all. ======================= Hello There. I have this small DLL that takes input_name and output_name as parameters. It opens the input file, reads it and produces output file with the specified name after some processing. I then call this function from C#. First time I call it, it runs fine. But second time around, it throws this exception An unhandled exception of System.AccessViolationException occured in CSharpProgram.exe. Attempted to read or write protected memory. Here is what I am trying.

        [DllImport("MyDll.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern int Call_Dll_Main(string input, string output);

        private void Button_Click(object sender, EventArgs ea)
        {
        new System.Threading.Thread(new System.Threading.ThreadStart(Call_Dll_Function)).Start()
        }

        private void Call_Dll_Function()
        {
        int nResult = Call_Dll_Main(txtInputFile.Text.Trim(), txtOutputFile.Text.Trim()); // HERE EXCEPTION COMES...FIRST TIME FINE...IT COMES SECOND TIME I CLICK THE BUTTON
        }

        What could be wrong? What am I missing here? Thanks for any input.

        L Offline
        L Offline
        Luc Pattyn
        wrote on last edited by
        #3

        Hi, I'm assuming you are using WinForms and those textXXXFile objects are Controls, maybe TextBoxes. A Control should only be created and used by a single thread, most often that would be the main or "GUI thread"; violating this rule is bound to give you AccessViolation trouble. I would recommend you use one (or more if you think you must) BackgroundWorker objects ibstead of bare Threads. A BGW will execute most of its task on a separate thread (which it borrows from the ThreadPool), however it also offers progress and completion events which execute on the main thread (assuming you created the BGW on the main thread) so all AccessViolations would disappear. If you're unfamiliar with the BGW class, read up on it, I'm pretty sure CP has some fine articles about it. Note 1: you should get the inputfile before entering the DoWork event. Note 2: you could reuse the BGW object, or create a new one, that is up to you. Note 3: there are some BGW properties you have to set true explicitly for it to activate all its goodies! good luck :)

        Luc Pattyn [My Articles] Nil Volentibus Arduum

        B 1 Reply Last reply
        0
        • D Django_Untaken

          The problem was in the unmanaged DLL. But I really learnt a great deal about other topics such as BackgroundWorkers and TPL. Thanks all. ======================= Hello There. I have this small DLL that takes input_name and output_name as parameters. It opens the input file, reads it and produces output file with the specified name after some processing. I then call this function from C#. First time I call it, it runs fine. But second time around, it throws this exception An unhandled exception of System.AccessViolationException occured in CSharpProgram.exe. Attempted to read or write protected memory. Here is what I am trying.

          [DllImport("MyDll.dll", CallingConvention = CallingConvention.Cdecl)]
          public static extern int Call_Dll_Main(string input, string output);

          private void Button_Click(object sender, EventArgs ea)
          {
          new System.Threading.Thread(new System.Threading.ThreadStart(Call_Dll_Function)).Start()
          }

          private void Call_Dll_Function()
          {
          int nResult = Call_Dll_Main(txtInputFile.Text.Trim(), txtOutputFile.Text.Trim()); // HERE EXCEPTION COMES...FIRST TIME FINE...IT COMES SECOND TIME I CLICK THE BUTTON
          }

          What could be wrong? What am I missing here? Thanks for any input.

          S Offline
          S Offline
          Slacker007
          wrote on last edited by
          #4

          pass the textbox values as parameters to Call_Dll_Function(). Remember that your thread can't access the controls from the UI thread - can't cross the streams. I personally would use the Task Parallel Library (TPL) for this. There are articles on this here at Codeproject. Check it out (Sacha Barber has some good ones). I use TPL often. Task Parallel Library: 1 of n[^]

          private void Call_Dll_Function(string input, string output)

          1 Reply Last reply
          0
          • D Django_Untaken

            The problem was in the unmanaged DLL. But I really learnt a great deal about other topics such as BackgroundWorkers and TPL. Thanks all. ======================= Hello There. I have this small DLL that takes input_name and output_name as parameters. It opens the input file, reads it and produces output file with the specified name after some processing. I then call this function from C#. First time I call it, it runs fine. But second time around, it throws this exception An unhandled exception of System.AccessViolationException occured in CSharpProgram.exe. Attempted to read or write protected memory. Here is what I am trying.

            [DllImport("MyDll.dll", CallingConvention = CallingConvention.Cdecl)]
            public static extern int Call_Dll_Main(string input, string output);

            private void Button_Click(object sender, EventArgs ea)
            {
            new System.Threading.Thread(new System.Threading.ThreadStart(Call_Dll_Function)).Start()
            }

            private void Call_Dll_Function()
            {
            int nResult = Call_Dll_Main(txtInputFile.Text.Trim(), txtOutputFile.Text.Trim()); // HERE EXCEPTION COMES...FIRST TIME FINE...IT COMES SECOND TIME I CLICK THE BUTTON
            }

            What could be wrong? What am I missing here? Thanks for any input.

            B Offline
            B Offline
            Bernhard Hiller
            wrote on last edited by
            #5

            Such Access Violation Exceptions often mean that a pointer pointed to some location which is outside of the process space of your program. And such things are more likely to happen in unmanaged code, i.e. the C dll. As we do not see the code of that dll, we can only speculate. It could be possible that the code tries to do something at the memory location of the strings it was passed at the first call, but Garbage Collection has removed them meanwhile.

            1 Reply Last reply
            0
            • L Luc Pattyn

              Hi, I'm assuming you are using WinForms and those textXXXFile objects are Controls, maybe TextBoxes. A Control should only be created and used by a single thread, most often that would be the main or "GUI thread"; violating this rule is bound to give you AccessViolation trouble. I would recommend you use one (or more if you think you must) BackgroundWorker objects ibstead of bare Threads. A BGW will execute most of its task on a separate thread (which it borrows from the ThreadPool), however it also offers progress and completion events which execute on the main thread (assuming you created the BGW on the main thread) so all AccessViolations would disappear. If you're unfamiliar with the BGW class, read up on it, I'm pretty sure CP has some fine articles about it. Note 1: you should get the inputfile before entering the DoWork event. Note 2: you could reuse the BGW object, or create a new one, that is up to you. Note 3: there are some BGW properties you have to set true explicitly for it to activate all its goodies! good luck :)

              Luc Pattyn [My Articles] Nil Volentibus Arduum

              B Offline
              B Offline
              Bernhard Hiller
              wrote on last edited by
              #6

              Accessing a control from a different thread results in an InvalidOperationException, e.g.

              Quote:

              Cross-thread operation not valid: Control 'button1' accessed from a thread other than the thread it was created on.

              1 Reply Last reply
              0
              • D Django_Untaken

                The problem was in the unmanaged DLL. But I really learnt a great deal about other topics such as BackgroundWorkers and TPL. Thanks all. ======================= Hello There. I have this small DLL that takes input_name and output_name as parameters. It opens the input file, reads it and produces output file with the specified name after some processing. I then call this function from C#. First time I call it, it runs fine. But second time around, it throws this exception An unhandled exception of System.AccessViolationException occured in CSharpProgram.exe. Attempted to read or write protected memory. Here is what I am trying.

                [DllImport("MyDll.dll", CallingConvention = CallingConvention.Cdecl)]
                public static extern int Call_Dll_Main(string input, string output);

                private void Button_Click(object sender, EventArgs ea)
                {
                new System.Threading.Thread(new System.Threading.ThreadStart(Call_Dll_Function)).Start()
                }

                private void Call_Dll_Function()
                {
                int nResult = Call_Dll_Main(txtInputFile.Text.Trim(), txtOutputFile.Text.Trim()); // HERE EXCEPTION COMES...FIRST TIME FINE...IT COMES SECOND TIME I CLICK THE BUTTON
                }

                What could be wrong? What am I missing here? Thanks for any input.

                M Offline
                M Offline
                Member 13260538
                wrote on last edited by
                #7

                Hello May I consult you how did u solved this problem? I have the similar problem [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate bool _B_B(byte O1, byte O2, byte O3, byte O4, byte O5); private IntPtr hMod; private _B_B funA; if (chk = (hMod = LoadLibrary("my.dll")) != IntPtr.Zero) if (chk = (pFunc = GetProcAddress(hMod, "funA")) != IntPtr.Zero) funA = (_B_B)Marshal.GetDelegateForFunctionPointer(pFunc, typeof(_B_B)); private void button_Click(object sender, EventArgs e) { bool chk = false; byte temp1 = 1, temp2 = 0, temp3 = 15, temp4 = 45, temp5 = 90; try { if (!(chk = funA(temp1, temp2, temp3, temp4, temp5))) MessageBox.Show("set fail!"); } catch (Exception ex) { MessageBox.Show("fail!"); } }

                D 1 Reply Last reply
                0
                • M Member 13260538

                  Hello May I consult you how did u solved this problem? I have the similar problem [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate bool _B_B(byte O1, byte O2, byte O3, byte O4, byte O5); private IntPtr hMod; private _B_B funA; if (chk = (hMod = LoadLibrary("my.dll")) != IntPtr.Zero) if (chk = (pFunc = GetProcAddress(hMod, "funA")) != IntPtr.Zero) funA = (_B_B)Marshal.GetDelegateForFunctionPointer(pFunc, typeof(_B_B)); private void button_Click(object sender, EventArgs e) { bool chk = false; byte temp1 = 1, temp2 = 0, temp3 = 15, temp4 = 45, temp5 = 90; try { if (!(chk = funA(temp1, temp2, temp3, temp4, temp5))) MessageBox.Show("set fail!"); } catch (Exception ex) { MessageBox.Show("fail!"); } }

                  D Offline
                  D Offline
                  Django_Untaken
                  wrote on last edited by
                  #8

                  My friend I don't remember what the issue was, but it was certainly in C++ dll. And that is what I updated the original post/question. Please double check C++ dll. Checkout this video tutorial

                  1 Reply Last reply
                  0
                  • D Django_Untaken

                    The problem was in the unmanaged DLL. But I really learnt a great deal about other topics such as BackgroundWorkers and TPL. Thanks all. ======================= Hello There. I have this small DLL that takes input_name and output_name as parameters. It opens the input file, reads it and produces output file with the specified name after some processing. I then call this function from C#. First time I call it, it runs fine. But second time around, it throws this exception An unhandled exception of System.AccessViolationException occured in CSharpProgram.exe. Attempted to read or write protected memory. Here is what I am trying.

                    [DllImport("MyDll.dll", CallingConvention = CallingConvention.Cdecl)]
                    public static extern int Call_Dll_Main(string input, string output);

                    private void Button_Click(object sender, EventArgs ea)
                    {
                    new System.Threading.Thread(new System.Threading.ThreadStart(Call_Dll_Function)).Start()
                    }

                    private void Call_Dll_Function()
                    {
                    int nResult = Call_Dll_Main(txtInputFile.Text.Trim(), txtOutputFile.Text.Trim()); // HERE EXCEPTION COMES...FIRST TIME FINE...IT COMES SECOND TIME I CLICK THE BUTTON
                    }

                    What could be wrong? What am I missing here? Thanks for any input.

                    U Offline
                    U Offline
                    User 1619902
                    wrote on last edited by
                    #9

                    Hi Django_Untaken did you solve this problem? I have the same problem. Thank in advance

                    1 Reply Last reply
                    0
                    Reply
                    • Reply as topic
                    Log in to reply
                    • Oldest to Newest
                    • Newest to Oldest
                    • Most Votes


                    • Login

                    • Don't have an account? Register

                    • Login or register to search.
                    • First post
                      Last post
                    0
                    • Categories
                    • Recent
                    • Tags
                    • Popular
                    • World
                    • Users
                    • Groups