【问题标题】:C#: Retrieving and using an IntPtr* through reflectionC#:通过反射检索和使用 IntPtr*
【发布时间】:2009-07-14 23:15:15
【问题描述】:

我目前正在编写一些代码,这些代码反映了从调用返回到本机 dll 的结构。一些结构包含指向以空值结尾的指针数组的 IntPtr* 字段。这些字段需要特殊处理。当反映结构时,我可以识别这些字段,因为它们是由自定义属性标记的。

以下说明了我正在尝试做的事情:

public void ProcessStruct(object theStruct)
{
    foreach (FieldInfo fi in theStruct.GetType().GetFields(BindingFlags.Public |  BindingFlags.Instance))
    {
        if (fi.FieldType.IsPointer && IsNullTermArray(fi))
        {
            //Has the custom attribute, commence processing of 
            //IntPtr* pointing to null-terminated array
            ProcessIntPtr(fi.GetValue(theStruct));
        }
        else{/*..Other Processing..*/  }
    }
}
public void unsafe ProcessIntPtr(IntPtr* ptr)
{
    //Iterate over the array and process the elements
    //There are pointer operations here.
}

问题是

  fi.GetValue(theStruct)

返回一个对象,我显然不能直接将它传递给 ProcessIntPtr()。我无法更改 ProcessIntPtr() 的签名以接受对象,因为那样我将无法执行所需的指针操作。显然,我也不能从对象转换为 IntPtr*。

有什么技术可以解决这个问题?

【问题讨论】:

    标签: c# reflection unsafe


    【解决方案1】:

    虽然您可能无法从 Object 转换为 IntPtr*,但您可以转换为 IntPtr。请记住,IntPtr* 只是一个指针指针。所以你可以得到第一个指针,然后把它扔回去。

    var ptr1 = (IntPtr)(fi.GetValue(theStruct));
    var ptr2 = (IntPtr*)(ptr1);
    

    【讨论】:

    • 我不是这方面的专家,但我认为您可能需要在这里使用 unsafe{ } ..对吗?
    • @Stan R,我也不是,但是是的,需要某种不安全的方式。
    • @Jared:这似乎更接近我的需要,但它会导致第一行出现无效的强制转换异常。
    • @David,如果你去 fi.GetValue(theStruct).GetType() 是什么类型
    • @Jared,这是一个 System.Reflection.Pointer。我意识到我需要调用 Pointer.Unbox() 。感谢您的帮助。
    【解决方案2】:

    要添加到 JaredPar 的答案,请查看 .NET 中的 Marshal 类,它可能对您有很多有用的功能。

    MSDN Link

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-07
      相关资源
      最近更新 更多