2017-08-26 102 views
-1

我创建了一个函数,允许我用当前打开的进程从内存中的指针返回一个泛型类型。ReadProcessMemory在多次调用后返回False

public static T ReadValue<T>(this IntPtr ptr, int length = 0) 
    { 
     Type valT = typeof(T); 
     byte[] buffer = length > 0 ? new byte[length] : new byte[Marshal.SizeOf(valT)]; 
     IntPtr retBytes; 
     object result; 

     if (!ReadProcessMemory(CurrentProcessHandle, ptr, buffer, buffer.Length, out retBytes)) 
      return default(T); 

     Console.WriteLine(ptr); 

     if (valT == typeof(byte)) 
      result = buffer[0]; 
     else if (valT == typeof(bool)) 
      result = buffer[0] > 0; 
     else if (valT == typeof(char)) 
      result = BitConverter.ToChar(buffer, 0); 
     else if (valT == typeof(double)) 
      result = BitConverter.ToDouble(buffer, 0); 
     else if (valT == typeof(float)) 
      result = BitConverter.ToSingle(buffer, 0); 
     else if (valT == typeof(int)) 
      result = BitConverter.ToInt32(buffer, 0); 
     else if (valT == typeof(long)) 
      result = BitConverter.ToInt64(buffer, 0); 
     else if (valT == typeof(object)) 
      result = buffer; 
     else if (valT == typeof(short)) 
      result = BitConverter.ToInt16(buffer, 0); 
     else if (valT == typeof(string)) 
      result = Encoding.Default.GetString(buffer); 
     else if (valT == typeof(uint)) 
      result = BitConverter.ToUInt32(buffer, 0); 
     else if (valT == typeof(ulong)) 
      result = BitConverter.ToUInt64(buffer, 0); 
     else if (valT == typeof(ushort)) 
      result = BitConverter.ToUInt16(buffer, 0); 
     else 
     { 
      IntPtr newVal = Marshal.AllocHGlobal(buffer.Length); 
      Marshal.Copy(buffer, 0, newVal, buffer.Length); 
      result = newVal; 
      Marshal.FreeHGlobal(newVal); 
     } 

     return (T) result; 
    } 

正在发生的事情是,经过〜39600个电话,ReadProcessMemory开始在以下呼叫100%返回false。起初,我认为这是IntPtr被复制和释放之前被不恰当地分配;但是,在删除IntPtr默认值后,问题仍然存在。这么多次被调用后会导致这个返回错误的是什么?

额外的编码信息:

是调用了ReadValue的对象。

​​

我所在的地方分配的IntPtr代码:这是无效的句柄

GameObject player = new GameObject().GetObjectFromIndex(1805); 
+0

使用['GetLastError'](https://msdn.microsoft.com/en-us/library/windows/desktop/ms679360(v = vs.85).aspx)无法找到更多关于问题。 – cubrr

+1

啊。谢谢你推荐我。它抛出错误代码(0x6),这是无效句柄。显然模块的句柄正在改变,所以我的指针不再正确。我感谢提示:) – Approved

+0

不错!一定要回答你的问题。 – cubrr

回答

-1

功能被扔错误代码(为0x6)。显然模块的句柄正在改变,所以我的指针不再正确。我通过在带有超时的while循环中封装函数来解决这个问题。如果函数的当前迭代小于超时,则在继续从内存读取数据之前,尝试再次获取句柄。

相关问题