2011-08-04 88 views
2

我试图从C++发送一个图像到C#托管的C++的互操作(编组)。 image->getStream()从字符串中返回一个const char*。我的Marshal::Copy函数有例外。从const char *复制到字节数组C++/c#interop Marshal ::复制

'System.AccessViolationException'类型的未处理的异常在mscorlib.dll发生

其他信息:试图读取或写入保护内存。这通常表明其他内存已损坏。

我在做从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; 
} 

图像由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; 
}; 
+0

什么类型是图像? System.Drawing.Image,它没有getStream()或getStreamSize()。我认为你的问题的根源在于流不是字节数组。 – shf301

+0

看到上面的代码,我发布了图像代码 – BuzBuza

+0

我的猜测是'wStream'不是'wLen'字节长度。真的不能告诉你。如果你添加'char temp = wStream [wLen-1]'你会得到一个访问冲突。 – shf301

回答

8

我不会用元帅:复制一个家。既然你有本地阵列,为什么不把它钉住并使用memcpy

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

现在,您可以拨打memcpyptrBuffer

当范围结束时,锁定自动取消。

+2

做到这一点,它比Marshal.Copy快得多,并且根本不应该伤害GC,正如@AresAvatar所说的那样,它一旦失去范围就会自动解锁。 –

+0

谢谢你的答案。我使用了memcpy。我直接复制到byteArray。的memcpy(字节阵列,wStream,WLEN)。问题是我的wStream是一个指向由ostringstream.str()。c_str()返回的本地const char *的指针。我没有现在str()返回一个缓冲区副本! – BuzBuza