Tutorial :Using unmanaged code in .net


The case:

There is a .net application calling unmanaged C code. Used method for this:

public static class MiracleCreator  {      [DllImport("Library.dll")]      private static extern void RunUnmanaged(string fileName);        public static void Run(string fileName)      {          RunUnmanaged(fileName);      }  }  

It is used in a Windows Forms application and the needed file name is obtained by OpenFileDialog. Code:

if (openFileDialog.ShowDialog() == DialogResult.OK)  {      MiracleCreator.Run(openFileDialog.FileName);  }  

The problem:

After several executions of the code in the Windows Forms application the openFileDialog gets broken with exception: "Attempted to read or write protected memory. This is often an indication that other memory is corrupt."

In searching for solution:

Trying "more reliable" use of OpenFileDialog doesn't help. Like this solution (tried to give the link, but "new users aren't allowed to add hyperlinks" :) ):

public class Invoker  {      public OpenFileDialog InvokeDialog;      private Thread InvokeThread;      private DialogResult InvokeResult;        public Invoker()      {          InvokeDialog = new OpenFileDialog();          InvokeThread = new Thread(new ThreadStart(InvokeMethod));          InvokeThread.SetApartmentState(ApartmentState.STA);          InvokeResult = DialogResult.None;      }        public DialogResult Invoke()      {          InvokeThread.Start();          InvokeThread.Join();          return InvokeResult;      }        private void InvokeMethod()      {          InvokeResult = InvokeDialog.ShowDialog();      }  }  

Usage :

        Invoker I = new Invoker();            if (I.Invoke() == DialogResult.OK)          {              MessageBox.Show(I.InvokeDialog.FileName, "Test Successful.");          }          else          {              MessageBox.Show("Test Failed.");          }  


Is the exception really caused by the unmanaged code? Could other possible problems be expected (breaking something different from the OpenFileDialog)? What is the better approach for this?

Thank you for every idea/solution.


You should specify the appropriate MarshalAs attribute for the string parameter of the method declaration. Something like:

[DllImport("Library.dll")]  private static extern void RunUnmanaged(    [MarshalAs(UnmanagedType. ... )] string fileName);  


Same errror using SaveFileDialog via managed code in a .NET Windows Forms application (running on Windows 7 32-bit) only when exposing the saveAs from a modal form with any data loaded from a db. After ugly hours of debug and trial/errors, my eyes fell on a property I did not realize was there before: in VB.NET, I wrote

Dim sfv As New System.Windows.Forms.SaveFileDialog     With sfv         .AutoUpgradeEnabled = False       '[...]   

and the error disappeared.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »