【问题标题】:Dereferencing a void* to a basic type in C++/CLI将 void* 取消引用到 C++/CLI 中的基本类型
【发布时间】:2015-02-18 23:46:31
【问题描述】:

如何取消引用 void* 在 C++/CLI 中指向的值,特别是,我想将其分配给 int。

int Callback(void* returnValue)
{
   int lookUpValue = *returnValue; // How to do this??

   if(lookUpValue==1)
     DoSomething();
   if(lookUpValue==2)
     DoSomethingElse();

    return CALLBACK_SUCCESS; // Defined elsewhere.
}

我试过了:

{
    GCHandle h = GCHandle::FromIntPtr(IntPtr(voidPtr));
    Object^ result = h.Target;
    lookUpValue = (int)result;
    h.Free();
}

来自示例: CLI/C++: void* to System::Object

但发现在某些情况下 h.Target 未定义,我会崩溃。所以不要认为我已经能够正确地做到这一点。

提前致谢。

【问题讨论】:

    标签: c++-cli unmanaged managed


    【解决方案1】:

    您不能直接取消引用void*,因为结果类型是未知的。在取消引用之前,您必须将 void* 转换为 int*

    int lookUpValue = *static_cast<int*>(returnValue);
    

    您找到的相关帖子不适用,因为 int 不是在 GC 堆上管理的对象,因此您无法获得它的 GC 句柄。

    【讨论】:

      猜你喜欢
      • 2011-08-28
      • 2014-03-11
      • 2011-07-20
      • 1970-01-01
      • 2011-06-17
      • 2014-07-23
      • 2012-05-23
      • 1970-01-01
      • 2010-11-12
      相关资源
      最近更新 更多