如何将托管c ++中的字节数组封送到c#

时间:2011-06-29 07:55:59

标签: c++ marshalling managed-c++

我想使用C ++托管项目中的.Net Graphic功能。我想从inmemory c ++字节数组创建Windows.Drawing.Image(基于MemoryStream)。

如何使这段代码有效:

System::IO::Stream^ ms = gcnew System::IO::MemoryStream();
BYTE buf[1024 * 8];  // C++
int size;  // C++
...
ms->Write(&buf, 0, size) 

提前谢谢!

1 个答案:

答案 0 :(得分:1)

你可以这样做:

int size = 1024;

BYTE buf[1024];

// unmanaged buffer
System::IntPtr intPtr = System::IntPtr( buf );

// managed buffer 
array<unsigned char>^ managedBuf = gcnew array<unsigned char>(size);

{
    // write things to buf[]
}

// copy unmanaged buffer to managed buffer
Marshal::Copy( intPtr, managedBuf, 0, size );

System::IO::Stream^ ms = gcnew System::IO::MemoryStream();

ms->Write( managedBuf, 0, size);