我目前正在研究一些代碼,它反映了從調用返回到本機dll的結構。一些結構包含IntPtr *字段,這些字段指向以null結尾的指針數組。這些字段需要特殊處理。在反思結構時,我可以識別這些字段,因爲它們由自定義屬性標記。C#:通過反射檢索和使用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 *。
有什麼技術可以解決這個問題?
我不是這方面的專家,但我想你可能需要使用不安全{} here..right? – 2009-07-14 15:19:50