开发者

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

I'm trying to send an image from C++ to C# with an interop (marshaling) of C++ managed. image->getStream() return a const char* from a string.

I'm having exception with my Mars开发者_高级运维hal::Copy function.

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

Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

Am I doing the right thing for the copy from a const char* to a byte array ? My dll is compiled with ASCII char set 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 home made C++ 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;
};


I wouldn't use Marshal::Copy. Since you have the array locally, why not just pin it and use memcpy?

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

You can now call memcpy to ptrBuffer.

When the scope ends the pinning is automatically undone.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜