gpt4 book ai didi

C#:通过反射检索和使用 IntPtr*

转载 作者:行者123 更新时间:2023-11-30 18:10:44 25 4
gpt4 key购买 nike

我目前正在编写一些代码,这些代码反射(reflect)了从对 native dll 的调用中编码返回的结构。一些结构包含指向以 null 结尾的指针数组的 IntPtr* 字段。这些字段需要特殊处理。反射(reflection)结构时,我可以识别这些字段,因为它们由自定义属性标记。

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

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*。

可以使用哪些技术来处理这个问题?

最佳答案

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

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

关于C#:通过反射检索和使用 IntPtr*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1126034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com