C#: Retrieving and using an IntPtr* through reflection

醉酒当歌 提交于 2019-12-12 14:27:54

问题


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.
}

The problem is that

  fi.GetValue(theStruct)

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?


回答1:


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);



回答2:


To add to JaredPar's answer, take a look at Marshal class in .NET , it might have a lot of useful features for you.

MSDN Link



来源:https://stackoverflow.com/questions/1126034/c-retrieving-and-using-an-intptr-through-reflection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!