从const char *复制到字节数组C ++ / c #interop Marshal :: Copy
我正在尝试将C ++中的图像发送到C#,并使用C ++管理的interop(marshaling)。 image->getStream()
从字符串返回一个const char*
。
我的Marshal::Copy
function有exception。
mscorlib.dll中发生了未处理的
'System.AccessViolationException'
类型exception附加信息:尝试读取或写入受保护的内存。 这通常表明其他内存已损坏。
我是否正在为从const char*
到字节数组的副本做正确的事情? 我的dll是在VS2010中使用ASCII字符集编译的。
array^ OsgViewer::getLastImage() { array^ byteArray; m_ImageQueue->lock(); int index = m_ImageQueue->getCurrentImageIndex(); std::shared_ptr image = m_ImageQueue->getImage(static_cast(index)); if( image && image->isValid() == true) { int wLen = image->getStreamSize(); char* wStream = const_cast(image->getStream()); byteArray = gcnew array(wLen); // convert native pointer to System::IntPtr with C-Style cast Marshal::Copy((IntPtr)wStream ,byteArray , 0, wLen); } m_ImageQueue->unlock(); return byteArray; }
Image是一个自制的C ++类
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; };
我不会使用Marshal :: Copy。 既然你在本地拥有这个数组,为什么不把它固定并使用memcpy
呢?
pin_ptr ptrBuffer = &byteArray[byteArray->GetLowerBound(0)];
您现在可以将memcpy
调用到ptrBuffer
。
当示波器结束时,固定将自动撤消。
上述就是C#学习教程:从const char *复制到字节数组C ++ / c #interop Marshal :: Copy分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/991473.html