Andrew Florko
Andrew Florko

Reputation: 7750

How do I marshal bytes array from managed c++ to c#

I'd like to use .Net Graphic functionality from C++ managed project. I'd like to create Windows.Drawing.Image (based on MemoryStream) from inmemory c++ array of bytes.

How can I make this piece of code work:

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

Thank you in advance!

Upvotes: 1

Views: 2019

Answers (1)

Sasha
Sasha

Reputation: 856

You can do it something like that:

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);

Upvotes: 1

Related Questions