主题:【文摘】C/C++圣战! -- aircobra
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csspec/html/vclrfcsharpspec_A_2.asp
C#的指针在Unsafe Block中使用,叫Unsafe code
While practically every pointer type construct in C or C++ has a reference type counterpart in C#, nonetheless, there are situations where access to pointer types becomes a necessity. For example, interfacing with the underlying operating system, accessing a memory-mapped device, or implementing a time-critical algorithm may not be possible or practical without access to pointers. To address this need, C# provides the ability to write unsafe code.
In unsafe code it is possible to declare and operate on pointers, to perform conversions between pointers and integral types, to take the address of variables, and so forth. In a sense, writing unsafe code is much like writing C code within a C# program.
Unsafe code is in fact a "safe" feature from the perspective of both developers and users. Unsafe code must be clearly marked with the modifier unsafe, so developers can't possibly use unsafe features accidentally, and the execution engine works to ensure that unsafe code cannot be executed in an untrusted environment.
顺便看一个小例子
using System;
class Test
{
static int value = 20;
unsafe static void F(out int* pi1, ref int* pi2) {
int i = 10;
pi1 = &i;
fixed (int* pj = &value) {
// ...
pi2 = pj;
}
}
static void Main() {
int i = 10;
unsafe {
int* px1;
int* px2 = &i;
F(out px1, ref px2);
Console.WriteLine("*px1 = {0}, *px2 = {1}",
*px1, *px2); // undefined behavior
}
}
}
- 相关回复 上下关系7
压缩 12 层
C#比JAVA更象C++。比如C#保留了指针,C#的delegate也更象C++ Highway 字389 2004-03-07 20:30:01
C#里没有指针。 无斋主人 字86 2004-03-09 11:33:47
.Net下面的Garbage Collection和Java的不太一样 老兵帅客 字538 2004-03-09 13:13:19
😮你说的是微软的C#吗?这里是指针(pointer)的使用说明。
这倒不知道。多谢! 无斋主人 字197 2004-03-09 14:49:49
😁C#里的pointer不由GC管理。你的想法是正确的。 Highway 字51 2004-03-09 14:55:05
的确如此 老兵帅客 字1100 2004-03-08 06:10:37