c# - 从 const char* 复制到字节数组 C++/c# interop Marshal::Copy

标签 c# c++ c++-cli marshalling

我正在尝试使用 C++ 管理的互操作(编码(marshal)处理)将图像从 C++ 发送到 C#。 image->getStream() 从字符串返回一个 const char*

我的 Marshal::Copy 函数出现异常。

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.

对于从 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)];

您现在可以调用memcpyptrBuffer

当范围结束时,固定会自动撤消。

关于c# - 从 const char* 复制到字节数组 C++/c# interop Marshal::Copy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6945998/

相关文章:

c# - 使用 HttpClient 的最佳实践

c# - 如何在 imagebutton 中显示来自 URL 的图像 - xamarin Android

c# - 具有同步和异步调用者的同步方法中的 Thread.Sleep 或 Task.Delay

c++ - 在图像QT 周围绘制边框。

c# - Xaml 中的 WPF 绑定(bind)

c++ - HoughLinesP 和 opencv 内存管理

c++ - Lua函数用C++返回字符串

c# - 将 c#/WPF GUI 围绕 c++/cli 围绕 native c++ 包装

c++-cli - 如何将(托管到非托管)数组<System::Byte ^>转换为byte *?

opencv - OpenCV和C++:全局cv::Mat对象返回错误的值