Share via


方法: アンマネージ リソースをバイト配列に読み込む

このトピックでは、アンマネージド リソースを Byte 配列に読み込むいくつかの方法について説明します。

アンマネージド リソースのサイズがわかっている場合は、CLR 配列を事前に割り当ててから、CLR 配列の配列ブロックへのポインターを使って、リソースを配列に読み込むことができます。

// 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

このサンプルで示すのは、アンマネージド メモリ ブロックからマネージド配列にデータをコピーする方法です。

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

関連項目

C++ Interop (暗黙の PInvoke) の使用