This topic has not yet been rated - Rate this topic

How to: Load Unmanaged Resources into a Byte Array

This topic discusses several ways to load unmanaged resources into a Byte array.

If you know the size of your unmanaged resource, you can preallocate a CLR array and then load the resource into the array using a pointer to the array block of the CLR array.

// load_unmanaged_resources_into_Byte_array.cpp
// compile with: /clr
using namespace System;
void unmanaged_func( unsigned char * p ) {
   for ( int i = 0; i < 10; i++ )
      p[ i ] = i;
}

public ref class A {
public:
   void func() {
      array<Byte> ^b = gcnew array<Byte>(10);
      pin_ptr<Byte> p =  &b[ 0 ];
      Byte * np = p;
      unmanaged_func( np );   // pass pointer to the block of CLR array.
      for ( int i = 0; i < 10; i++ )
         Console::Write( b[ i ] );
      Console::WriteLine();
   }
};

int main() {
   A^ g = gcnew A;
   g->func();
}
0123456789

This sample shows how to copy data from an unmanaged memory block to a managed array.

// load_unmanaged_resources_into_Byte_array_2.cpp
// compile with: /clr
using namespace System;
using namespace System::Runtime::InteropServices;

#include <string.h>
int main() {
   char buf[] = "Native String";
   int len = strlen(buf);
   array<Byte> ^byteArray = gcnew array<Byte>(len + 2);
   
   // convert any native pointer to IntPtr by doing C-Style cast
   Marshal::Copy( (IntPtr)buf, byteArray, 0, len );
}
Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Performance concerns
Neither of these examples provide optimal bytes /  performance. The Marshal class in general, while helpful, has poor execution performance. Pinning the array and copying the content is better, but you should copy 8 bytes / 64 bits / a long at a time, then if the array length is not aligned, copy the potentially remaining 1 to 7 bytes, for faster performance (8 bytes is one CPU register / 1 operation).
Advertisement