我在使用C#通过这个P/Invoke签名调用
代码非常相似,但由于某种原因,对缓冲区的引用丢失了,并且缓冲区被设置为null。如果这不是一个外部调用,我可以百分之百确定这是一个bug,因为缓冲区没有作为
使情况更加奇怪的是,当我将该代码替换为:
这段代码本来就是可以正常工作的。包括内存读取等!所以所有发生的事情都是由于某种原因导致
这种行为是我的问题吗(比如说有错误的P/Invoke),它是否危险(会泄漏内存),并且能否解释清楚呢?
编辑: 我使用的完整NativeMethods类可以在此处找到:http://paste2.org/p/2770271 编辑2: 我添加了简单的步骤来解决问题,答案可以在此处找到:https://dev59.com/aW3Xa4cB1Zd3GeqPeGbQ#14410443。
ReadProcessMemory
时遇到了一些非常奇怪的行为:[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool ReadProcessMemory(
IntPtr hProcess,
IntPtr lpBaseAddress,
[Out] byte[] lpBuffer,
int dwSize,
out int lpNumberOfBytesRead
);
在我的应用程序中,我正在扫描具有读写访问权限的内存区域的整个内存(并应用一些其他过滤器,但那是另一个部分)。
扫描部分的代码大致如下:
int numberOfBytes;
if (!NativeMethods.ReadProcessMemory(handle, region.StartAddress,
buffer, (int)region.RegionSize, out numberOfBytes))
// The handle, region (custom struct containing some fields from the
// MEMORY_BASIC_INFORMATION struct), and buffer come from parameters.
这段代码在IT技术中表现良好。它扫描整个内存以查找一系列字节,没有任何问题。
在我的程序流程中稍微有些不同,我有这段代码:
注意:它使用与前面代码相同的IntPtr句柄(已检查),并在同一线程中运行
int bytesRead;
byte[] buffer = new byte[128]; // In my real app this is some calculated value
// however that irrelevant. It's calculated 128.
if (!NativeMethods.ReadProcessMemory(handle, location.Location,
buffer, buffer.Length, out bytesRead))
continue; // Error while reading
// At this point buffer == null, so the next line causes an exception
if (bytesRead != buffer.Length) continue;
代码非常相似,但由于某种原因,对缓冲区的引用丢失了,并且缓冲区被设置为null。如果这不是一个外部调用,我可以百分之百确定这是一个bug,因为缓冲区没有作为
ref
或out
参数传递。然而,我知道.NET在涉及外部调用时会进行一些神秘的操作(例如marshaling)。使情况更加奇怪的是,当我将该代码替换为:
int bytesRead;
byte[] buffer = new byte[128];
byte[] bufferRef = buffer;
if (!NativeMethods.ReadProcessMemory(handle, location.Location,
buffer, buffer.Length, out bytesRead))
continue; // Error while reading
buffer = bufferRef;
if (bytesRead != buffer.Length) continue;
这段代码本来就是可以正常工作的。包括内存读取等!所以所有发生的事情都是由于某种原因导致
buffer
变量失去了对实际缓冲区的引用。这让我非常困惑。
这种行为是我的问题吗(比如说有错误的P/Invoke),它是否危险(会泄漏内存),并且能否解释清楚呢?
我的配置:
- .NET Framework 4.0
- Visual Studio Professional 2012(版本11.0.51106.01 Update 1)
- 安装了.NET Framework 4.5.50709
- 以管理员身份运行
- 在Visual Studio主机可执行文件和常规构建可执行文件中均出现
- Windows 7 64位
- 我正在从中读取内存的进程是32位的
- 构建配置:平台:任何CPU
编辑: 我使用的完整NativeMethods类可以在此处找到:http://paste2.org/p/2770271 编辑2: 我添加了简单的步骤来解决问题,答案可以在此处找到:https://dev59.com/aW3Xa4cB1Zd3GeqPeGbQ#14410443。