Jen*_*nix 3 c# pointers unsafe fixed
我fixed
用数组和字符串变量测试了关键字并且工作得非常好,但我不能使用单个变量.
static void Main() {
int value = 12345;
unsafe {
fixed (int* pValue = &value) { // problem here
*pValue = 54321;
}
}
}
Run Code Online (Sandbox Code Playgroud)
该行fixed (int* pValue = &value)
导致编译器错误.我没有得到它,因为变量value
不在unsafe
块中而且还没有固定.
为什么我不能fixed
用于变量value
?
Tho*_*que 13
这是因为value
是一个局部变量,在堆栈上分配,所以它已经修复了.错误消息中提到了这一点:
CS0213您不能使用fixed语句获取已修复表达式的地址
如果您需要地址value
,则不需要该fixed
声明,您可以直接获取:
int* pValue = &value;
Run Code Online (Sandbox Code Playgroud)