这是实现本机 pinvok 代码的类
尽管我无法验证它是否正确使用不安全的代码,但它似乎有效
不安全的签名
struct IO_COUNTERS
{
public ulong ReadOperationCount;
public ulong WriteOperationCount;
public ulong OtherOperationCount;
public ulong ReadTransferCount;
public ulong WriteTransferCount;
public ulong OtherTransferCount;
}
[DllImport("kernel32.dll")]
unsafe static extern bool GetProcessIoCounters(IntPtr* ProcessHandle, out IO_COUNTERS IoCounters);
我的“不安全”代码
public static unsafe class IO
{
public static Dictionary<string, ulong> GetALLIO(Process procToRtrivIO)
{
IO_COUNTERS counters;
Dictionary<string, ulong> retCountIoDict = new Dictionary<string, ulong>();
GetProcessIoCounters((IntPtr*)System.Diagnostics.Process.GetCurrentProcess().Handle, out counters);
retCountIoDict.Add("ReadOperationCount", counters.ReadOperationCount);
retCountIoDict.Add("WriteOperationCount", counters.WriteOperationCount);
retCountIoDict.Add("OtherOperationCount", counters.OtherOperationCount);
retCountIoDict.Add("ReadTransferCount", counters.ReadTransferCount);
retCountIoDict.Add("WriteTransferCount", counters.WriteTransferCount);
retCountIoDict.Add("OtherTransferCount", counters.OtherTransferCount);
return retCountIoDict;
//return "This process has read " + ((counters.ReadTransferCount/1024)/1024).ToString("N0") +
// " Mb of data.";
}
}
现在,在我的另一个问题中建议了下一个代码块(就在我设法编译和运行上面的代码之前,...因为我遇到了一些问题)
所以就在我通过反复试验解决了我的问题之后,有人发布了这个部分解决方案,这是部分原因,它不包括两者
struct
,signeture
所以我问它是否正在测试,因为它确实编译但不运行。我的意思是当它运行时(没有编译错误)但在运行时,错误是
An exception of type 'System.NullReferenceException' occurred in App_Code.1ri3mog1.dll but was not handled in user code
附加信息:对象引用未设置为对象的实例。
所以这是我从上一个问题中得到的代码
Ok you need to change a few things, shown below
public static class IO
{
unsafe public static Dictionary<string, ulong> GetALLIO(Process procToRtrivIO)
{
IO_COUNTERS* counters;
Dictionary<string, ulong> retCountIoDict = new Dictionary<string, ulong>();
IntPtr ptr = System.Diagnostics.Process.GetCurrentProcess().Handle;
GetProcessIoCounters(&ptr, out counters);
retCountIoDict.Add("ReadOperationCount", counters->ReadOperationCount);
retCountIoDict.Add("WriteOperationCount", counters->WriteOperationCount);
retCountIoDict.Add("OtherOperationCount", counters->OtherOperationCount);
retCountIoDict.Add("ReadTransferCount", counters->ReadTransferCount);
retCountIoDict.Add("WriteTransferCount", counters->WriteTransferCount);
retCountIoDict.Add("OtherTransferCount", counters->OtherTransferCount);
return retCountIoDict;
//return "This process has read " + ((counters.ReadTransferCount/1024)/1024).ToString("N0") +
// " Mb of data.";
}
}
所以问题是,我真的做到了......并且安全地使用了不安全的代码(代码的顶部块)或者我错过了一些东西,如果我的代码没问题(我仍然怀疑它没有完全使用不安全的配件),建议的代码版本有什么问题?