如何:使用 C++ Interop 封送處理內嵌指標
下列程式代碼範例會使用 Managed、Unmanaged #pragma 指示詞,在相同的檔案中實作 Managed 和 Unmanaged 函式,但如果在個別檔案中定義,這些函式會以相同方式互操作。 僅包含 Unmanaged 函式的檔案不需要使用 /clr 進行編譯(Common Language Runtime 編譯)。
範例
下列範例示範如何從Managed函式呼叫接受包含指標之結構的 Unmanaged 函式。 Managed 函式會建立 結構的實例,並使用 new 關鍵詞來初始化內嵌指標(而不是 ref new,gcnew 關鍵詞)。 由於這會在原生堆積上配置記憶體,因此不需要釘選陣列來隱藏垃圾收集。 不過,必須明確刪除記憶體,以避免記憶體外洩。
// marshal_embedded_pointer.cpp
// compile with: /clr
#include <iostream>
using namespace System;
using namespace System::Runtime::InteropServices;
// unmanaged struct
struct ListStruct {
int count;
double* item;
};
#pragma unmanaged
void UnmanagedTakesListStruct(ListStruct list) {
printf_s("[unmanaged] count = %d\n", list.count);
for (int i=0; i<list.count; i++)
printf_s("array[%d] = %f\n", i, list.item[i]);
}
#pragma managed
int main() {
ListStruct list;
list.count = 10;
list.item = new double[list.count];
Console::WriteLine("[managed] count = {0}", list.count);
Random^ r = gcnew Random(0);
for (int i=0; i<list.count; i++) {
list.item[i] = r->NextDouble() * 100.0;
Console::WriteLine("array[{0}] = {1}", i, list.item[i]);
}
UnmanagedTakesListStruct( list );
delete list.item;
}
[managed] count = 10
array[0] = 72.624326996796
array[1] = 81.7325359590969
array[2] = 76.8022689394663
array[3] = 55.8161191436537
array[4] = 20.6033154021033
array[5] = 55.8884794618415
array[6] = 90.6027066011926
array[7] = 44.2177873310716
array[8] = 97.754975314138
array[9] = 27.370445768987
[unmanaged] count = 10
array[0] = 72.624327
array[1] = 81.732536
array[2] = 76.802269
array[3] = 55.816119
array[4] = 20.603315
array[5] = 55.888479
array[6] = 90.602707
array[7] = 44.217787
array[8] = 97.754975
array[9] = 27.370446