views:

281

answers:

1

I'm using a dll that contains unmanaged code for interacting with specific hardware, and I'm trying to use it from C#, but I keep getting an AccessViolationException.

What's causing it, and how can I fix it?

namespace FingerPrint {
    public unsafe partial class Form1 : Form {

        [DllImport("MyDll.dll")]
        public static extern int DoesExist();

        public unsafe Form1() {
            InitializeComponent();

            MessageBox.Show(DoesExist() + "");
        }
    }
}
+1  A: 

Roughly 95% of all failure modes for unmanaged code produce an access violation. You can trigger such a failure mode by getting the [DllImport] declaration wrong. But DoesExist() as posted cannot trigger one.

Contact the vendor or the author of the DLL for support. They should have little trouble reproducing the fault and diagnosing it with a debugger and their source code if you got it to fail so easily.

For completeness, the most typical causes of AccessViolation:

  • a memory management bug in the unmanaged code, causing heap corruption
  • not validating data, causing null dereferences or buffer overflows
  • not checking for failure return error codes when calling support functions
Hans Passant
Strangely, his example has no input parameters or return values.
Danny Varod