Marshalling a variable from int to struct in 64X

Viewed 135

When my application is running on x86 the program works fine. When I run it on x64, the Access Violation exception occurs. Exception details mentioned below.

"System.AccessViolationException: 'Attempted to read or write protected memory. This is often an indication that other memory is corrupt.'"

I thought that the problem lies in Marshalling. Do I have to manually Marshal the structure? Need help on this. I would prefer to have the same struct for both x64 and x86. My native method is defined like below.

[StructLayout(LayoutKind.Sequential)]
   internal struct CWPSTRUCT
  {
   internal IntPtr lParam;
   internal IntPtr wParam;
   internal int message;
   internal IntPtr hwnd;
  }

And the CallNextHookEx is,

[DllImport("user32", CharSet=CharSet.Auto, ExactSpelling=true)]
        extern public static IntPtr CallNextHookEx(IntPtr hhook, int code, int wparam, int lparam)  ;

And the method in which exception occurs,

private IntPtr MessageHookProc(int nCode, int wParam, int lParam, ref bool processMessage)  
        {
            GC.KeepAlive(this);
            if (nCode >= 0 && !this.DisableMessageHook)
            {
                IMessageFilter imf = client as IMessageFilter;
                if (imf != null)
                {
                    **CWPSTRUCT cwp = 
                        (CWPSTRUCT)(Marshal.PtrToStructure((IntPtr)lParam, typeof(CWPSTRUCT)));**

                    Message msg = Message.Create(cwp.hwnd, cwp.message, cwp.wParam, cwp.lParam);

                    if(imf.PreFilterMessage(ref msg))
                    {
                        processMessage = false;
                        return (IntPtr)1;
                    }
                }
            }

            return NativeHookMethods.CallNextHookEx(this.MessageHookHandle,nCode,wParam,lParam);
        }

And the code in which the particular method-MessageHookProc used,

WndProcHooker messageHooker = (WndProcHooker)this.reference.Target;
retval = messageHooker.MessageHookProc(nCode,wParam,lParam, ref processMessage);
0 Answers
Related