title: Destructor execution when wrapping a C++ object for using with C# PInvoke
body: <p>I have a C++ class that I want to use in C#. For doing so I am trying to write an other C++ dll to wrap this class (which is part of an other library) with invokable functions (using "extern C and __declspec(dllexport)").
  My idea is to keep a pointer to my object and send it to functions in wrapper dll and then call methods of that object from there. This seems fine but problems happen when object has deconstructor.</p>
  
  <p>Here is my C++ wrapper code: (Device is my C++ class/object)</p>
  
  <pre><code>__declspec(dllexport) Status Device_open(Device* di, const char* uri)
  {
       Device dl;
       Status status = dl.open(uri);
       di = &amp;dl;
       return status;
  }
  __declspec(dllexport) void Device_Close(Device* di)
  {
       di-&gt;close();
  }
  </code></pre>
  
  <p>Here is my C# wrapper code:</p>
  
  <pre><code>    [DllImport("Wrapper.dll")]
      static extern Status Device_open(ref IntPtr objectHandler, IntPtr uri);
      public static Device Open(string uri)
      {
          IntPtr handle = IntPtr.Zero;
          Device_open(ref handle, Marshal.StringToHGlobalAnsi(uri));
          return new Device(handle);
      }
      [DllImport("Wrapper.dll")]
      static extern void Device_Close(IntPtr objectHandler);
      public void Close()
      {
          Device_Close(this.Handle);
      }
  </code></pre>
  
  <p>Here is testing code in C# application:</p>
  
  <pre><code>    Device d = Device.Open(di.URI);
      d.Close();
  </code></pre>
  
  <p>Every thing is good. Problem is here that when I request opening a new device, Deconstructor of main C++ object will be executed so my close request always return exception (becouse it is already closed or destructed);</p>
  
  <p>What can I do to prevent this?!</p>