interior_ptr :
msdn: 点击打开链接
托管类型不能直接转换成非托管类型,只能使用interior_ptr,声明个指针,里面存放托管类型变量的引用,然后才能对其使用。
例如有一个类
ref class MyClass {
public:
int data;
};
下面的代码,编译时出错
MyClass ^ h_MyClass = gcnew MyClass;
h_MyClass->data = 1;
Console::WriteLine(h_MyClass->data);
int* np = &(h_MyClass->data);
*np = 4;
错误信息:
1>(18): error C2440: 'initializing' : cannot convert from 'cli::interior_ptr<Type>' to 'int *'
1> Cannot convert a managed type to an unmanaged type
应该用下面的代码修正:
MyClass ^ h_MyClass = gcnew MyClass;
h_MyClass->data = 1;
Console::WriteLine(h_MyClass->data);
interior_ptr<int> p = &(h_MyClass->data);
*p = 2;
Console::WriteLine(h_MyClass->data);
interior_ptr :能够防止被引用的托管对象,不被垃圾回收。
(用pin_ptr可以代替
interior_ptr ??)