【发布时间】:2021-12-13 01:41:56
【问题描述】:
所以我使用以下代码从内存中读取:
public static extern bool ReadProcessMemory(IntPtr handle, IntPtr baseAddress, [Out] byte[] buffer, int size, out IntPtr numberOfBytesRead);
它使用上面的代码将内存十六进制代码输出为字节数组:
buffer[0] = 01;
buffer[1] = 2D;
buffer[2] = F2;
我想在某个十六进制代码范围内搜索某个十六进制数组。 为此,我想使用“KMP Algorithm for Pattern Searching”。
目前我正在使用以下代码来实现:
byte[] moduleBytes = {0};
IntPtr bytesRead;
ReadProcessMemory(process.Handle, baseAddress, moduleBytes, moduleBytes.Length, out bytesRead);
string buffer = "";
foreach (byte bytesfrommemory in moduleBytes)
{
buffer += bytesfrommemory.ToString("X");;
}
//algorithm
string data = buffer;
int[] value = SearchString(data, pattern);
foreach (int entry in value)
{
Console.WriteLine(entry); //Outputs the offset where it found the code
}
问题在于循环遍历每个字节以将其添加到缓冲区字符串需要 +1000 个字节的时间。有没有更快的方法将字节数组从数组“转换”为字符串,而无需实际转换它,因为我仍然需要原始字节数组作为字符串?
我用下面的代码试过了,但是它把它转换成不同的东西:
char[] characters = moduleBytes.Select(o => (char)o).ToArray();
string buffer = new string(characters);
感谢您的帮助:)
【问题讨论】:
-
附加到字符串非常慢,因为您每次都需要创建一个全新的字符串。试试
var bufferBuilder = new StringBuilder(); foreach (byte moduleByte in moduleBytes) { bufferBuilder.Append(moduleByte.ToString("F")); } string data = bufferBuilder.ToString(); -
您应该能够执行使用字节数组(及其长度)作为输入的 KMP 实现。
-
@CamiloTerevinto 显然 OP 已经看过 "byte array to hex and back" 问题(为什么他们选择最糟糕的例子来添加到这个问题很难说,但这并不重要) - 他们要求“没有转换“ 代码。有点令人困惑的部分是为什么他们根本需要字符串,因为所有“字符串搜索”算法都适用于值序列而不是
string(一旦尝试在搜索之前尝试翻译/提取字符串的含义)...