不能使用 fixed语句获得已固定的表达式的地址?这是怎么回事?

appletan 2006-04-10 11:16:39
using System;
public class addrsOpr
{
unsafe public static int Main(string[] args)
{
// addrsOpr.cs
// A C# program demonstrating how to use
// the Binary AND operator & to return
// the address of an unsafe value
// PROGRAM DOES NOT COMPILE - erad last comment!!!
// Copyright (c) Chris H. Pappas and William H. Murray, 2001
//

Console.WriteLine("& used on true AND true = {0}", true & true);
Console.WriteLine("& used on true AND false = {0}", true & false);

int iValue = 4;

// the following "fixed" block IS crrect - hower,
// the program will NOT compile - WHY?
fixed(int *pi = &iValue)
{
string hexAddress = int.Format((int)pi, "x");
Console.WriteLine("& returning address of iValue: {0}", hexAddress);

// or the simpler version, not using teh string variable
Console.WriteLine("& returning address of iValue: {0}", int.Format((int)pi, "x"));
}

// to get addrsOpr.cs to compile and execute
// your MUST remember - ANY method using unsafe pointers
// must include the "unsafe" keyword in the method prototype
// when you change Main()'s prototype to:
// unsafe public static int Main(string[] args)
// the program will compile and execute!

return 0;
}
}
...全文
627 1 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
lw8122 2006-05-29
  • 打赏
  • 举报
回复
I corrected your code. You can try to compile it again.
Don't forget set project option "allow unsafe code" to "true"


using System;
public class addrsOpr
{
int iValue = 4;

unsafe public static int Main(string[] args)
{
// addrsOpr.cs
// A C# program demonstrating how to use
// the Binary AND operator & to return
// the address of an unsafe value
// PROGRAM DOES NOT COMPILE - erad last comment!!!
// Copyright (c) Chris H. Pappas and William H. Murray, 2001
//

Console.WriteLine("& used on true AND true = {0}", true & true);
Console.WriteLine("& used on true AND false = {0}", true & false);


// the following "fixed" block IS crrect - hower,
// the program will NOT compile - WHY?
fixed(int *pi = &iValue)
{
string hexAddress = ((int)pi).ToString("x");
Console.WriteLine("& returning address of iValue: {0}", hexAddress);

// or the simpler version, not using teh string variable
Console.WriteLine("& returning address of iValue: {0}", ((int)pi).ToString("x"));
}

// to get addrsOpr.cs to compile and execute
// your MUST remember - ANY method using unsafe pointers
// must include the "unsafe" keyword in the method prototype
// when you change Main()'s prototype to:
// unsafe public static int Main(string[] args)
// the program will compile and execute!

return 0;
}
}


111,093

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧