title: Trouble with C#<->C++ DLLImport "Attempted to read or write protected memory."
body: <p>I have a C++ dll which has a function within it I am trying to call from a C# application.</p>
  
  <p>Here's the code in the C++ header file</p>
  
  <pre><code>extern "C" _declspec(dllexport) int LabelStoringSSDsim(int devNum, UCHAR serial[40], UCHAR wwn[40],
                  UCHAR ConfigID[5], UCHAR FrmRev[8], UCHAR DevName[40], int eCode);
  </code></pre>
  
  <p>Here's the code in the C++ source file</p>
  
  <pre><code>int LabelStoringSSDsim(int devNum, UCHAR serialLbl[40], UCHAR wwnLbl[40],
                  UCHAR ConfigID[5], UCHAR FrmRev[8], UCHAR DevName[40], int eCode)
  {
  
      string strConfigID="12111";                                     //5 bytes
      string strFrmRev="1.25....";                                    //8 bytes
      string strDevName="ABC-123.................................";   //40 bytes
  
      for (int i=0;i&lt;5;i++)
          ConfigID[i] = strConfigID[i];
  
      for (int i=0;i&lt;8;i++)
          FrmRev[i] = strFrmRev[i];
  
      for (int i=0;i&lt;40;i++)
          DevName[i] = strDevName[i];
      return eCode;
  }
  </code></pre>
  
  <p>Here's the C# relevant code</p>
  
  <pre><code>[DllImport("LabelStoring.dll")]
  static extern int LabelStoringSSDsim(
      int devNum,
      byte[] strserial,
      byte[] strwwn,
      [In] ref byte[] ConfigID,
      [In] ref byte[] FrmRev,
      [In] ref byte[] DevName,
      int eCode
  );
  
  
  int errNum = LabelStoringSSDsim(devNum, bserial, bwwn, ref ConfigID, ref FrmRev, ref DevName, 123123);
  </code></pre>
  
  <p>So when I get to the last bit of code there I get the "Attempted to read or write protected memory. This is often an indication that other memory is corrupt." error.</p>
  
  <p>I have no prior experience in importing DLL's like this and I've done a lot of searching but cannot seem to find a solution to the problem.</p>
  
  <p>I tried starting over from scratch with a simple function returning an integer, and that worked. Then I added an int for me to pass to the function and it still worked. Then I added a byte array for me to pass, which worked. Then I attempted to turn that byte array into a reference and it failed. So my guess is I'm getting the data back incorrectly.</p>
  
  <p>Any help is greatly appreciated.</p>