我正在尝试使用 C++ 管理的互操作(编码(marshal)处理)将图像从 C++ 发送到 C#。 image->getStream()
从字符串返回一个 const char*
。
我的 Marshal::Copy
函数出现异常。
An unhandled exception of type
'System.AccessViolationException'
occurred in mscorlib.dllAdditional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
对于从 const char*
到字节数组的复制,我做的事情是否正确?我的 dll 是用 VS2010 中的 ASCII 字符集编译的。
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是一个自制的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<Byte> ptrBuffer = &byteArray[byteArray->GetLowerBound(0)];
您现在可以调用memcpy
到ptrBuffer
。
当范围结束时,固定会自动撤消。
关于c# - 从 const char* 复制到字节数组 C++/c# interop Marshal::Copy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6945998/