C#:通过反射检索和使用 IntPtr* [英] C#: Retrieving and using an IntPtr* through reflection

查看:57
本文介绍了C#:通过反射检索和使用 IntPtr*的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm currently working on some code which reflects over structures that are marshaled back from calls into a native dll. Some of the structs contain IntPtr* fields that point to null-terminated arrays of pointers. These fields require special processing. When reflecting over the structs, I can recognize these fields because they are marked by a custom attribute.

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

The following illustrates what I'm trying to do:

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() 的签名以接受对象,因为那样我将无法执行所需的指针操作.显然,我也不能从 object 转换为 IntPtr*.

returns an object, which I obviously can't pass directly to ProcessIntPtr(). I cannot change the signature of ProcessIntPtr() to accept an object, as then I wouldn't be able to perform the pointer operations that I require. Obviously, I also can't cast from object to IntPtr*.

有哪些技术可以处理这个问题?

What techniques are available to handle this issue?

推荐答案

虽然您可能无法从 Object 转换为 IntPtr*,但您可以转换为 IntPtr.请记住,IntPtr* 只是一个指针指针.所以你可以到达第一个指针,然后将它转换回来.

While you may not be able to cast from Object to IntPtr*, you can cast to IntPtr. Remember, IntPtr* is just a pointer pointer. So you can get to the first pointer and then cast it back.

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

这篇关于C#:通过反射检索和使用 IntPtr*的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆