C# – Using P/Invoke correctly


I need to call an external dll from c#. This is the header definition:

enum WatchMode { 
   WATCH_MODE_SYSTEM = 0,          

LONG ADS_API WDT_GetMode ( LONG i_hHandle, WatchMode * o_pWatchMode );

I've added the enum and the call in C#:

public enum WatchMode
internal static extern long WDT_GetMode(long hHandle, ref WatchMode watchmode);

This generates an AccessViolationException. I know the dll is 'working' because I've also added a call to GetHandle which returns the hHandle mentioned above. I've tried to change the param to an int (ref int watchmode) but get the same error. Doesn anyone know how I can PInvoke the above call?

Best Solution

You're running into a parameter size problem difference between C# and C++. In the C++/windows world LONG is a 4 byte signed integer. In the C# world long is a 8 byte signed integer. You should change your C# signature to take an int.

ffpf is wrong in saying that you should use an IntPtr here. It will fix this particular problem on a 32 bit machine since an IntPtr will marshal as a int. If you run this on a 64 bit machine it will marshal as a 8 byte signed integer again and will crash.