int* Get_x( X* pX )
{
int __pin* ppx = &pX->x;
return ppx;
// DANGER: ppx goes of scope, so object pointed by it is no
// longer pinned, making the return value unsafe.
}
不应进行如下操作:使用已钉住指针获得变量的地址,然后在钉住指针离开范围后使用该地址。
// keyword_pin_scope_bad.cpp
// compile with: /clr /LD
#using <mscorlib.dll>
__gc struct X
{
int x;
};
int* Get_x( X* pX )
{
int __pin* px = &pX -> x;
return px; // BE CAREFUL px goes of scope,
// so object pointed by it is no longer pinned,
// making the return value unsafe.
}
// keyword_pin_scope_good.cpp
// compile with: /clr /LD
#using <mscorlib.dll>
__gc struct X
{
int x;
};
int Get_x( X* pX )
{
int __pin* px = &pX -> x;
return *px; // OK, value obtained from px before px out of scope
}
示例
在下面的示例中,pG 指向的对象被一直钉住,直到它移动到范围外:
class H
{
public:
// unmanaged function
void incr(int * i)
{
(*i)++;
std::cout << *i << std::endl;
};
};
int main()
{
G __pin * pG = new G; // pG is a pinning pointer
H * h = new H;
// pointer to managed data passed as actual parameter of unmanaged
// function call
h->incr(& pG -> i);
}
输出
1
请参见
C++ 托管扩展参考 | C++ 关键字 | PinningPtr 示例