using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
namespace CSharpUnsafeCodesLab
{
internal class Program
{
private const string CscPath = @"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe";
private static string RunProc(string fileName, string arguments, out int exitCode)
{
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = fileName;
psi.Arguments = arguments;
psi.UseShellExecute = false;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
psi.StandardOutputEncoding = Encoding.UTF8;
psi.StandardErrorEncoding = Encoding.UTF8;
psi.CreateNoWindow = true;
using (Process p = Process.Start(psi))
{
string stdout = p.StandardOutput.ReadToEnd();
string stderr = p.StandardError.ReadToEnd();
p.WaitForExit(30000);
exitCode = p.ExitCode;
return (stdout + stderr).Trim();
}
}
private static string Esc(string s)
{
if (s == null) return "null";
StringBuilder sb = new StringBuilder("\"");
foreach (char c in s)
{
switch (c)
{
case '\\': sb.Append("\\\\"); break;
case '"': sb.Append("\\\""); break;
case '\n': sb.Append("\\n"); break;
case '\r': sb.Append("\\r"); break;
case '\t': sb.Append("\\t"); break;
default:
if (c < 32) sb.AppendFormat("\\u{0:x4}", (int)c);
else sb.Append(c);
break;
}
}
sb.Append("\"");
return sb.ToString();
}
private static string CaseJson(string name, string summary, string expected, string actual)
{
bool passed = string.Equals(expected, actual, StringComparison.Ordinal);
return string.Format(
"{{\"name\":{0},\"summary\":{1},\"expected\":{2},\"actual\":{3},\"passed\":{4}}}",
Esc(name), Esc(summary), Esc(expected), Esc(actual), passed ? "true" : "false"
);
}
public static void Main(string[] args)
{
Console.OutputEncoding = Encoding.UTF8;
List<string> cases = new List<string>();
string tempDir = Path.Combine(Path.GetTempPath(), "csharplab-unsafe-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tempDir);
try
{
string innerCs = Path.Combine(tempDir, "UnsafeRunner.cs");
string innerExe = Path.Combine(tempDir, "UnsafeRunner.exe");
string innerCode =
"using System;\n" +
"using System.Text;\n" +
"class UnsafeRunner {\n" +
" static unsafe void Swap(int* p, int* q) {\n" +
" int temp = *p;\n" +
" *p = *q;\n" +
" *q = temp;\n" +
" }\n" +
" static void Main() {\n" +
" Console.OutputEncoding = Encoding.UTF8;\n" +
" unsafe {\n" +
" int val = 20;\n" +
" int* p1 = &val, p2 = &val;\n" +
" int** pp = &p1;\n" +
" void* vp = p1;\n" +
" char ch = 'Z';\n" +
" char* cp = &ch;\n" +
" double dbl = 1.5;\n" +
" double* dp = &dbl;\n" +
" float flt = 2.5f;\n" +
" float* fp = &flt;\n" +
" int*[] ptrArr = new int*[1];\n" +
" ptrArr[0] = p2;\n" +
" bool ptrNonZero = ((long)p1 != 0 && (long)vp == (long)p1 && **pp == 20 && *ptrArr[0] == 20 && *cp == 'Z' && *dp == 1.5 && *fp == 2.5f);\n" +
" Console.WriteLine(\"DEREF:\" + val + \":\" + p1->ToString() + \":\" + ptrNonZero);\n" +
" int a = 10, b = 20;\n" +
" Swap(&a, &b);\n" +
" Console.WriteLine(\"SWAP:\" + a + \",\" + b);\n" +
" int[] list = { 10, 100, 200 };\n" +
" fixed (int* ptr = list) {\n" +
" long stride = (long)(ptr + 1) - (long)ptr;\n" +
" Console.WriteLine(\"FIXED:\" + *(ptr) + \",\" + *(ptr + 1) + \",\" + *(ptr + 2) + \":stride=\" + stride);\n" +
" }\n" +
" int* stackBuf = stackalloc int[3];\n" +
" stackBuf[0] = 10; stackBuf[1] = 20; stackBuf[2] = 30;\n" +
" int stackSum = stackBuf[0] + stackBuf[1] + stackBuf[2];\n" +
" Console.WriteLine(\"STACK:\" + stackSum);\n" +
" }\n" +
" }\n" +
"}\n";
File.WriteAllText(innerCs, innerCode, Encoding.UTF8);
// Case 1: Compile without /unsafe fails with CS0227; compile with /unsafe succeeds
int noFlagExit;
string noFlagOut = RunProc(CscPath, string.Format("/nologo /utf8output /out:\"{0}\" \"{1}\"", innerExe, innerCs), out noFlagExit);
bool failedWithCS0227 = (noFlagExit != 0 && noFlagOut.IndexOf("CS0227", StringComparison.Ordinal) >= 0);
int withFlagExit;
RunProc(CscPath, string.Format("/nologo /utf8output /unsafe /out:\"{0}\" \"{1}\"", innerExe, innerCs), out withFlagExit);
string actual1 = string.Format("noFlagCS0227={0};withUnsafeExit={1}", failedWithCS0227, withFlagExit);
cases.Add(CaseJson(
"csc_requires_unsafe_flag",
"Verify csc.exe rejects unsafe pointers with CS0227 unless /unsafe switch is supplied",
"noFlagCS0227=True;withUnsafeExit=0",
actual1
));
// Execute compiled real /unsafe binary and parse deterministic output lines
int runExit;
string runOut = RunProc(innerExe, "", out runExit);
string[] lines = runOut.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
string derefLine = lines.Length > 0 ? lines[0] : "";
string swapLine = lines.Length > 1 ? lines[1] : "";
string fixedLine = lines.Length > 2 ? lines[2] : "";
string stackLine = lines.Length > 3 ? lines[3] : "";
// Case 2: Pointer dereference, p->ToString(), multi-pointer decl & all 7 pointer forms
cases.Add(CaseJson(
"unsafe_pointer_deref_and_tostring",
"Execute real /unsafe binary verifying &var, p->ToString(), int* p1,p2, int**, void*, int*[], char*, double*, float*",
"exit=0|DEREF:20:20:True",
string.Format("exit={0}|{1}", runExit, derefLine)
));
// Case 3: Passing pointers as method parameters (Swap)
cases.Add(CaseJson(
"unsafe_pointer_swap_parameter",
"Execute real /unsafe Swap(int* p, int* q) mutating caller stack variables 10,20 -> 20,10",
"SWAP:20,10",
swapLine
));
// Case 4: fixed array pinning, sizeof(int)==4 pointer stride, and stackalloc
cases.Add(CaseJson(
"unsafe_fixed_array_and_stackalloc",
"Execute real /unsafe fixed(int* ptr = list) traversal (stride=4) and stackalloc int[3] sum=60",
"FIXED:10,100,200:stride=4|STACK:60",
fixedLine + "|" + stackLine
));
}
finally
{
if (Directory.Exists(tempDir))
{
Directory.Delete(tempDir, true);
}
}
Console.WriteLine(string.Format(
"{{\"version\":\"csc4/{0}\",\"cases\":[{1}]}}",
Environment.Version.ToString(),
string.Join(",", cases.ToArray())
));
}
}
}
本例需在 Windows x64、.NET Framework 4.x Visual C# 编译器(csc.exe)本地离线环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、.NET Framework 4.x Visual C# 编译器(csc.exe)本地离线环境。
入口文件:projects/csharp-unsafe-codes-lab/ExploreUnsafeCodes.cs
本地运行步骤快速上手
- 点击上方“保存源码”保存为
ExploreUnsafeCodes.cs,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、.NET Framework 4.x Visual C# 编译器(csc.exe)本地离线环境。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联42章) · 含当前章节或实例 · mbskycom202612a1321.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1358.zip