示例:联合搜索结构体
本示例以屏幕宽度 750、高度 1334 为例(请根据实际设备调整)。
本示例希望通过 screen.image 获取屏幕内容,得到图片对象并赋值给某一变量,然后通过内存联合搜索的方式去修改此图片对象,使其高度减半。
结构体定义
首先,已知 NBTouch 用于截取屏幕图像的缓冲区结构体如下:
struct JST_IMAGE {
uint8_t orientation;
int32_t width;
int32_t alignedWidth;
int32_t height;
void *pixels;
uint8_t isDestroyed;
};
搜索条件
因此,我们需要在脚本进程的内存中搜索出所有符合以下条件的结构体:
{
{ lv = 750, type = "I32" }, -- width
{ lv = 750, hv = 800, type = "I32", offset = 4 }, -- alignedWidth
{ lv = 1334, type = "I32", offset = 8 }, -- height
}
示例代码
--
-- 进行一次屏幕截图,将图片对象赋值给一个变量
local img = screen.image()
--
-- 获取脚本进程的进程号
local posix = require("posix")
local pid = posix.getpid().pid
--
-- 搜索所有符合条件的结构体
local data, err
data, err = memory.search(pid, true, 0, {
{ lv = 750, type = "I32" },
{ lv = 750, hv = 800, type = "I32", offset = 4 },
{ lv = 1334, type = "I32", offset = 8 },
}, "U8", 10)
assert(data, err)
assert(#data > 0, "无法搜索到符合条件的结构体。")
--
-- 遍历找到的结构体
local orientation, width, alignedWidth, height, pixels, isDestroyed
for i, v in ipairs(data) do
--
-- 读取结构体的各个字段
orientation, err = memory.read(pid, v - 4, "U8")
assert(orientation, err)
width, err = memory.read(pid, v, "I32")
assert(width, err)
alignedWidth, err = memory.read(pid, v + 4, "I32")
assert(alignedWidth, err)
height, err = memory.read(pid, v + 8, "I32")
assert(height, err)
pixels, err = memory.read(pid, v + 12, "U64")
assert(pixels, err)
isDestroyed, err = memory.read(pid, v + 20, "U8")
assert(isDestroyed, err)
--
-- 打印结构体的各个字段
sys.alert(string.format(
"第 %d 个结构体:\n" ..
"orientation = %d\n" ..
"width = %d\n" ..
"alignedWidth = %d\n" ..
"height = %d\n" ..
"pixels = %d\n" ..
"isDestroyed = %d",
i, orientation, width, alignedWidth, height, pixels, isDestroyed
))
--
-- 修改指定的图像高度为原来的一半
if isDestroyed == 0 and height == 1334 then
local ok
ok, err = memory.write(pid, v + 8, "I32", 667)
assert(ok, err)
sys.alert("已修改第 " .. i .. " 个结构体的 height 字段为 667。")
end
end
--
-- 检查图片对象是否修改成功
local _, h = img:size()
assert(h == 667, "图片对象的高度未修改成功。")
img:save_to_album()
sys.alert("图片对象的高度已修改成功,点击 "好" 以结束本示例。")