Copy from const char * to C ++ / C # byte array interop Marshal :: Copy

I am trying to send an image from C ++ to C # using interop (marshaling) managed C ++. image->getStream() returns a const char* from the string.

I have an exception with my Marshal::Copy function.

An unhandled exception of type 'System.AccessViolationException' occurred in mscorlib.dll

Additional Information: Attempted to read or write protected memory. This often indicates that another memory is corrupted.

Am I doing the right thing for a copy from const char* to an array of bytes? My dll is compiled with an ASCII char installed in VS2010.

 array<System::Byte>^ OsgViewer::getLastImage() { array< Byte >^ byteArray; m_ImageQueue->lock(); int index = m_ImageQueue->getCurrentImageIndex(); std::shared_ptr<Image> image = m_ImageQueue->getImage(static_cast<unsigned int>(index)); if( image && image->isValid() == true) { int wLen = image->getStreamSize(); char* wStream = const_cast<char*>(image->getStream()); byteArray = gcnew array< Byte >(wLen); // convert native pointer to System::IntPtr with C-Style cast Marshal::Copy((IntPtr)wStream ,byteArray , 0, wLen); } m_ImageQueue->unlock(); return byteArray; } 

Image is a C ++ home class

 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; }; 
+2
c ++ c # marshalling c ++ - cli
source share
1 answer

I would not use Marshal :: Copy. Since you have an array locally, why not just attach it and use memcpy ?

 pin_ptr<Byte> ptrBuffer = &byteArray[byteArray->GetLowerBound(0)]; 

Now you can call memcpy in ptrBuffer .

When the area ends, the pinning is automatically canceled.

+8
source share

All Articles