title: Error: Calling C++ dll function in C#
body: <p>I am trying to use functions in C++ dll from C#, but I got an error: "attempt to read or write protected memory. This is often indication that other memory is corrupt"</p>
  
  <p>Anyone know how to fix ?</p>
  
  <p>Here is C++ functions:</p>
  
  <pre><code>typedef void *DGNHandle;
  
   __declspec(dllexport) DGNHandle CPL_DLL    DGNOpen( const char *, int );
   __declspec(dllexport) DGNElemCore CPL_DLL *DGNReadElement( DGNHandle )
  </code></pre>
  
  <p>Here is structure in C++:</p>
  
  <pre><code>typedef struct {
      int         offset;
      int         size;
  
      int         element_id;     /*!&lt; Element number (zero based) */
      int         stype;          /*!&lt; Structure type: (DGNST_*) */
      int         level;          /*!&lt; Element Level: 0-63 */
      int         type;           /*!&lt; Element type (DGNT_) */
      int         complex;        /*!&lt; Is element complex? */
      int         deleted;        /*!&lt; Is element deleted? */
  
      int         graphic_group;  /*!&lt; Graphic group number */
      int         properties;     /*!&lt; Properties: ORing of DGNPF_ flags */
      int         color;          /*!&lt; Color index (0-255) */
      int         weight;         /*!&lt; Line Weight (0-31) */
      int         style;          /*!&lt; Line Style: One of DGNS_* values */
  
      int         attr_bytes;     /*!&lt; Bytes of attribute data, usually zero. */
      unsigned char *attr_data;   /*!&lt; Raw attribute data */
  
      int         raw_bytes;      /*!&lt; Bytes of raw data, usually zero. */
      unsigned char *raw_data;    /*!&lt; All raw element data including header. */
  } DGNElemCore; 
  </code></pre>
  
  <p>And below converted codes are in C#:</p>
  
  <pre><code>[StructLayout(LayoutKind.Sequential )]
      public class DGNElemCore
      {
          public int attr_bytes;
          public byte[] attr_data;
          public int color;
          public int complex;
          public int deleted;
          public int element_id;
          public int graphic_group;
          public int level;
          public int offset;
          public int properties;
          public int raw_bytes;
          public byte[] raw_data;
          public int size;
          public int style;
          public int stype;
          public int type;
          public int weight;
  
      }
  
  [DllImport("DgnLib.dll", EntryPoint = "DGNOpen")]
          public static extern IntPtr  DGNOpen(string fileName, int bUpdate);
  [DllImport("DgnLib.dll", EntryPoint = "DGNReadElement")]
          public static extern DGNElemCore DGNReadElement(IntPtr DGNHandle)
  </code></pre>
  
  <p>Codes for testing:</p>
  
  <pre><code>DGNElemCore element = new DGNElemCore();
  element = DgnFile.DGNReadElement(dgnFile.oDgnFile) **//Throw error**
  </code></pre>