【问题标题】:Why can't get address of variable in unsafe-statement?为什么不能在不安全的语句中获取变量的地址?
【发布时间】:2013-02-26 20:43:26
【问题描述】:

根据 MSDN,我们可以在不安全的上下文中获取变量的地址。
我们可以在不安全声明的方法中获取变量的地址,但为什么不能在所有不安全的上下文中获取它?

static void Main(string[] args) {      
    //Managed code here
    unsafe {
        string str = "d";
        fixed (char* t = &str[0]) {// ERROR :  Cannot take the address of the given expression
        }
    }
    //Managed code here
}

【问题讨论】:

  • 什么是g?它是如何失败的?
  • 您看到的错误/行为是什么?
  • 对不起,我会更新问题
  • 请指明是哪一行报错。
  • @evanmcdonnal 错误出现在固定线路上。

标签: c#


【解决方案1】:

这只是无效的 C# 语法。字符串不是数组,它只是看起来像一个。试试:

unsafe 
{
   string str = "d";
   fixed (char* t = str) 
   {
       char c1 = *t;
       char c2 = t[0];
   }
}

【讨论】:

  • 这不是 MSDN 所说的(或者至少不是我的理解)。来自 fixed 上的 msdn 页面 - fixed (char* p = str) ... // equivalent to p = &str[0]
  • 等效并不意味着两者都会编译。 str[0] 是一个索引器,不能在 &str[0]Foo(ref str[0]) 中工作
  • 是的,我并不是说这不能解决问题,只是 MSDN 文档具有误导性。
  • @HenkHolterman 根据 MSDN fixed (char* p = str) 是有效的。并且抛出错误无法将类型'string*'隐式转换为'char*'。存在显式转换(您是否缺少演员表?
  • 在其他答案上查看我关于 string* 的 cmets。
【解决方案2】:

获取字符串地址的正确方法是这样的:

char* t = str

http://msdn.microsoft.com/en-us/library/f58wzh21.aspx

【讨论】:

  • 这也没用。错误:无法将类型“string*”隐式转换为“char*”。存在显式转换(您是否缺少演员表?)
  • str 不是 string* 所以你错过了什么吗?
  • @Mahdi 你忘了把它放在一个固定的语句中吗?
  • 这是我使用的unsafe {string str = "d"; fixed (char* t = &str) {}}
猜你喜欢
  • 2021-08-06
  • 2021-11-24
  • 2012-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-10
相关资源
最近更新 更多