title: PInvoke "Attempted to read or write protected memory"
body: <p>I'm wrapping a C DLL (which I only have .h's) and I'm stuck with "Attempted to read or write protected memory".</p>
  
  <p><strong>Info:</strong></p>
  
  <ul>
  <li>Windows 7 64-bit</li>
  <li>DLL is 64-bit</li>
  <li>C# App and Wrapper is 64-bit</li>
  </ul>
  
  <p><strong>Export Def:</strong></p>
  
  <pre><code>#if defined(_WIN32) &amp;&amp; !defined(__SYMBIAN32__)
  #define EXP_API __cdecl
  #else
      #if !defined(__SYMBIAN32__)
          #define EXP_API
      #else
          #define EXP_API EXPORT_C
      #endif
  #endif
  </code></pre>
  
  <p><strong>Here is the C header struct:</strong></p>
  
  <pre><code>typedef struct bufferstrm bufferstrm_tt;
  
  struct bufferstrm
  {
    uint32_t  (EXP_API * bytes_usage)(bufferstrm_tt *bs);
  
    uint8_t * (EXP_API * get_stuff)(bufferstrm_tt *bs, uint32_t length);
  
  
    struct implstrm* some_struct;
  };
  
  int32_t EXP_API strmParser(struct bufferstrm_tt *bs);
  </code></pre>
  
  <p><strong>My C# Wrapper:</strong></p>
  
  <pre><code>[DllImport("Parser.dll", EntryPoint = "strmParser", CallingConvention = CallingConvention.Cdecl)]
  public static extern int strmParser(ref bufferstrm bs);
  
  // Delegates
  [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
  public delegate uint BUFSTRM_bytes_usage(ref bufferstrm bs);
  [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
  public delegate IntPtr BUFSTRM_get_stuff(ref bufferstrm bs, uint length);
  
  [StructLayout(LayoutKind.Sequential)]
  public struct bufferstrm
  {
     public BUFSTRM_bytes_usage bytes_usage;
  
     public BUFSTRM_get_stuff get_stuff;
  
     public IntPtr some_struct;
  }
  
  [StructLayout(LayoutKind.Sequential)]
  public struct implstrm
  {
     public uint dummy;
  }
  
  public static uint test_bytes_usage(ref bufferstrm bs)
  {
     return 0;
  }
  
  public static IntPtr test_get_stuff(ref bufferstrm bs, uint length)
  {
     return IntPtr.Zero;
  }
  </code></pre>
  
  <p><strong>If I use it like this:</strong> [Attempted to read or write protected memory]</p>
  
  <pre><code>bufferstrm bs = new bufferstrm();
  bs.bytes_usage = BUFSTRM_bytes_usage(test_bytes_usage);
  bs.get_stuff = BUFSTRM_get_stuff(test_get_stuff);
  implstrm testStruct = new implstrm();
  IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(testStruct)));
  Marshal.StructureToPtr(testStruct, ptr, false);
  bs.some_struct = ptr;
  
  int hr = strmParser(ref bs);
  </code></pre>
  
  <p>If I don't set the callbacks it just returns the predicted hr value (which is missing stuff).</p>
  
  <p>Anyone has any idea what am I doing wrong?</p>
  
  <p>Thank you!</p>
  
  <p>EDIT:</p>
  
  <p>Enabling "Unmanaged Code Debuggin" I got "Access violation reading location 0xffffffffffffffff". Does this tell you guys anything?</p>