共用方式為


如何:使用 C++ Interop 封送處理陣列

本主題示範 Visual C++互操作性的一個 Facet。 如需詳細資訊,請參閱 使用 C++ Interop (隱含 PInvoke)

下列程式代碼範例會使用 Managed、Unmanaged #pragma 指示詞,在相同的檔案中實作 Managed 和 Unmanaged 函式,但如果在個別檔案中定義,這些函式會以相同方式互操作。 僅包含 Unmanaged 函式的檔案不需要使用 /clr 進行編譯(Common Language Runtime 編譯)。

範例:將Managed數位傳遞至 Unmanaged 函式

下列範例示範如何將 Managed 陣組傳遞至 Unmanaged 函式。 Managed 函式會在呼叫 Unmanaged 函式之前,先使用 pin_ptr (C++/CLI) 來隱藏數位的垃圾收集。 藉由將釘選的指標提供給 Unmanaged 函式至 GC 堆積,即可避免建立數位複本的額外負荷。 為了示範 Unmanaged 函式正在存取 GC 堆積記憶體,它會修改數位的內容,並在 Managed 函式繼續控制時反映變更。

// PassArray1.cpp
// compile with: /clr
#ifndef _CRT_RAND_S
#define _CRT_RAND_S
#endif

#include <iostream>
#include <stdlib.h>
using namespace std;

using namespace System;

#pragma unmanaged

void TakesAnArray(int* a, int c) {
   cout << "(unmanaged) array received:\n";
   for (int i=0; i<c; i++)
      cout << "a[" << i << "] = " << a[i] << "\n";

   unsigned int number;
   errno_t err;

   cout << "(unmanaged) modifying array contents...\n";
   for (int i=0; i<c; i++) {
      err = rand_s( &number );
      if ( err == 0 )
         a[i] = number % 100;
   }
}

#pragma managed

int main() {
   array<int>^ nums = gcnew array<int>(5);

   nums[0] = 0;
   nums[1] = 1;
   nums[2] = 2;
   nums[3] = 3;
   nums[4] = 4;

   Console::WriteLine("(managed) array created:");
   for (int i=0; i<5; i++)
      Console::WriteLine("a[{0}] = {1}", i, nums[i]);

   pin_ptr<int> pp = &nums[0];
   TakesAnArray(pp, 5);

   Console::WriteLine("(managed) contents:");
   for (int i=0; i<5; i++)
      Console::WriteLine("a[{0}] = {1}", i, nums[i]);
}

範例:將 Unmanaged 陣列傳遞至 Managed 函式

下列範例示範如何將 Unmanaged 陣列傳遞至 Managed 函式。 Managed 函式會直接存取數位記憶體(而不是建立 Managed 陣列並複製數位內容),這可讓 Managed 函式在重新取得控制權時反映在 Unmanaged 函式中所做的變更。

// PassArray2.cpp
// compile with: /clr
#include <iostream>
using namespace std;

using namespace System;

#pragma managed

void ManagedTakesAnArray(int* a, int c) {
   Console::WriteLine("(managed) array received:");
   for (int i=0; i<c; i++)
      Console::WriteLine("a[{0}] = {1}", i, a[i]);

   cout << "(managed) modifying array contents...\n";
   Random^ r = gcnew Random(DateTime::Now.Second);
   for (int i=0; i<c; i++)
      a[i] = r->Next(100);
}

#pragma unmanaged

void NativeFunc() {
   int nums[5] = { 0, 1, 2, 3, 4 };

   printf_s("(unmanaged) array created:\n");
   for (int i=0; i<5; i++)
      printf_s("a[%d] = %d\n", i, nums[i]);

   ManagedTakesAnArray(nums, 5);

   printf_s("(ummanaged) contents:\n");
   for (int i=0; i<5; i++)
      printf_s("a[%d] = %d\n", i, nums[i]);
}

#pragma managed

int main() {
   NativeFunc();
}

另請參閱

使用 C++ Interop (隱含 PInvoke)