title: Copy from const char* to a byte array C++/c# interop Marshal::Copy
body: <p>I'm trying to send an image from C++ to C# with an interop (marshaling) of C++ managed. <code>image-&gt;getStream()</code> return a <code>const char*</code> from a string.</p>
  <p>I'm having exception with my <code>Marshal::Copy</code> function.</p>
  <blockquote>
  <p>An unhandled exception of type <code>'System.AccessViolationException'</code> occurred in mscorlib.dll</p>
  <p>Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.</p>
  </blockquote>
  <p>Am I doing the right thing for the copy from a <code>const char*</code> to a byte array ? My dll is compiled with ASCII char set in VS2010.</p>
  <pre class="lang-cpp prettyprint-override"><code>array&lt;System::Byte&gt;^ OsgViewer::getLastImage()
  {
      array&lt; Byte &gt;^ byteArray;
  
      m_ImageQueue-&gt;lock();
  
      int index = m_ImageQueue-&gt;getCurrentImageIndex();
      std::shared_ptr&lt;Image&gt; image = m_ImageQueue-&gt;getImage(static_cast&lt;unsigned int&gt;(index));
      if( image &amp;&amp; image-&gt;isValid() == true)
      {
          int wLen = image-&gt;getStreamSize();
          char* wStream = const_cast&lt;char*&gt;(image-&gt;getStream());
          byteArray = gcnew array&lt; Byte &gt;(wLen);
  
          // convert native pointer to System::IntPtr with C-Style cast
          Marshal::Copy((IntPtr)wStream ,byteArray , 0, wLen);
      }
  
      m_ImageQueue-&gt;unlock();
      return byteArray;
  }
  </code></pre>
  <p>Image is a home made C++ class</p>
  <pre class="lang-cpp prettyprint-override"><code>class ADAPTER Image
  {
  public :
      Image();
      ~Image();
      const char* getStream() const;
      int getStreamSize();
      bool setStringStream(std::ostringstream* iStringStream);
      void setIsValid(bool isValid){ m_isValid = isValid;}
      bool isValid() const{return m_isValid;}
      std::ostringstream* getOStringStream() {return m_StringStream;}
  private:
      std::ostringstream* m_StringStream;
      bool m_isValid;
  };
  </code></pre>