2008-10-29 46 views
2
void f(cli::array<PointF> ^points){ 
    PointF& a = points[0]; 
    // and so on... 
} 

編譯錯誤在第2行C++/CLI參考變

.\ndPanel.cpp(52) : error C2440: 'initializing' : cannot convert from 'System::Drawing::PointF' to 'System::Drawing::PointF &' 
     An object from the gc heap (element of a managed array) cannot be converted to a native reference 

什麼是聲明一個參考變量的管理方法是什麼?

回答

3

如果你只是想聲明數組中第一個的PointF的引用,那麼你需要使用tracking reference(%):

void f(cli::array<PointF>^ points) 
{  
    PointF% a = points[0]; 
} 
1

您需要使用gcroot模板從vcclr.h文件:

這些樣品從MSDN:

// mcpp_gcroot.cpp 
// compile with: /clr 
#include <vcclr.h> 
using namespace System; 

class CppClass { 
public: 
    gcroot<String^> str; // can use str as if it were String^ 
    CppClass() {} 
}; 

int main() { 
    CppClass c; 
    c.str = gcnew String("hello"); 
    Console::WriteLine(c.str); // no cast required 
} 

// mcpp_gcroot_2.cpp 
// compile with: /clr 
// compile with: /clr 
#include <vcclr.h> 
using namespace System; 

struct CppClass { 
    gcroot<String ^> * str; 
    CppClass() : str(new gcroot<String ^>) {} 

    ~CppClass() { delete str; } 

}; 

int main() { 
    CppClass c; 
    *c.str = gcnew String("hello"); 
    Console::WriteLine(*c.str); 
} 

// mcpp_gcroot_3.cpp 
// compile with: /clr 
#include <vcclr.h> 
using namespace System; 

public value struct V { 
    String^ str; 
}; 

class Native { 
public: 
    gcroot<V^> v_handle; 
}; 

int main() { 
    Native native; 
    V v; 
    native.v_handle = v; 
    native.v_handle->str = "Hello"; 
    Console::WriteLine("String in V: {0}", native.v_handle->str); 
} 

你會發現更多的here

+0

gcroot只是一個快捷方式的GCHandle,而不是本身的參考。它用於通過將託管對象固定在託管堆中來使本機類指向並使用託管對象。 – 2008-10-29 13:21:33

0

,這裏是你的代碼更改爲使用gcroot:

void f(cli::array<gcroot<PointF ^>> points){ 
    gcroot<PointF ^> a = points[0]; 
    // and so on... }